Communitygithub.com

SwiftUIエキスパート

クリーンで高性能、アクセシブルなSwiftUIビューを構築し、正しい状態の所有権、スコープ指定された無効化、スムーズなリストスクロールを実現します。既存のSwiftUIコードをフレームタイムと再レンダリング予算に基づいてレビューします。

SwiftUIエキスパート とは?

このスキルは、SwiftUIアプリケーションにおける状態管理とパフォーマンス最適化の専門知識を提供します。正しい状態の所有権(@State、@Binding、@Observable、@Environment)を選択し、ビューの無効化を影響を受けるビューに限定することで、不必要な再レンダリングを防止します。120HzのProMotionデバイスと60Hzのベースラインデバイスの両方でフレーム予算の維持を保証し、スクロール時のスタッターを排除します。また、アニメーションの駆動、VoiceOver対応、Dynamic Typeなどのアクセシビリティ要件をデフォルトで組み込みます。このスキルは、具体的なコード例を用いて「悪い」状態設計と「良い」状態設計を比較し、実際のパフォーマンス改善を示します。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/SkillMedev/skills/tree/HEAD/skills/swift-ui

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

SwiftUIエキスパート は何をしますか?

SwiftUIの画面は状態の所有権でその命運が決まります。間違った場所に状態を置くと、キー入力のたびにツリー全体が再評価され、リストがスタッターし、アニメーションが引き裂かれます。このスキルは、無効化が変更されたデータを実際に読み取るビューに限定され、スクロール中もフレーム予算が維持され、結果的にアクセシビリティが後付けではなくデフォルトで確保されるように、SwiftUIビューを構築およびレビューします。

操作手順

状態設計が下流のすべてを決定するため、この順序で作業します。状態を修正するよりも後にビュー階層が構築されていると、階層を書き直す必要があります。

ステップ1: 入力の収集

ビューコードを記述する前に収集します。ユーザーが不明な場合はデフォルトを使用し、推測であることを明記します。

  • ターゲットデバイスとリフレッシュレート(デフォルト:ProMotion 120Hz iPhoneと60Hzベースラインデバイスの両方を想定)。
  • データの形状:最大のリスト内のアイテム数、データがどの程度の頻度で変更されるか、ストリーミングされるかどうか。
  • 所有権マップ:状態の各ピースについて、どのビューが作成し、どのビューが読み取り、どのビューが変更するか。
  • ベースライン以上のアクセシビリティ要件(デフォルト:完全なDynamic Type + VoiceOverサポート)。

ステップ2: 値ごとの状態所有権の選択

機能する最も狭いラッパーを選択します。

  • @State - ローカル、ビュー所有、値型の状態。ビューが作成する@Observableモデルインスタンスの正しい所有者でもあります。
  • @Binding - 他の場所で所有されている状態への双方向参照。子が変更する場合にのみバインディングを渡し、読み取り専用の場合はプレーンな値を渡します。
  • @Observable(Observationフレームワーク) - モデルオブジェクト。ビューは読み取ったプロパティのみを監視するため、無効化はオブジェクト単位ではなくプロパティ単位です。
  • @Environment - サービスや共有モデルのための依存性注入をツリーに下ろします。

ルール:状態は、それを読み取りまたは書き込みするすべてのビューの最も近い共通祖先に配置します。それより下(ビューが非表示になるとリセットされる)でも上(無効化が広がる)でもありません。

ステップ3: 無効化をスコープするためのビューの構成

  • bodyを小さく保ちます。サブビューを抽出することで、変更が画面全体ではなく1行のみを無効化します。約50行または3レベルのネストを超えるbodyは分割候補です。
  • サブビューには最小限のデータのみを渡します。ストア全体ではなくitem.titleを渡すことで、影響を受けるビューのみが再レンダリングされます。
  • 巨大なネストされたクロージャの代わりに@ViewBuilderヘルパーを使用します。
  • body内で重い処理(フォーマット、ソート、フィルタリング、デコード)を決して行わないでください。モデルで計算し、ビューには完成した値を渡します。bodyはマイクロ秒の範囲に保つ必要があります。アニメーション中は毎フレーム実行される可能性があるためです。

ステップ4: リストとフレーム予算

予算は120Hzで1フレームあたり8.3ms、60Hzで16.7msです。これはそのフレームのメインスレッド上のすべての処理であり、単一の行の処理だけではありません。実用的なルール:

  • 約50行を超える場合はListまたはLazyVStackを使用し、行が必要に応じてレンダリングされるようにします。ScrollView内のプレーンなVStackはすべての行を事前に構築します。
  • アイテムにはデータから安定したid(item.id)を割り当て、配列インデックスやbody内で計算されたUUID()は決して使用しないでください。不安定なIDは行の同一性を破壊し、ちらつき、スクロール位置の喪失、行状態の喪失を引き起こします。
  • 行は一定コストでなければなりません。行ごとの日付フォーマッターや画像デコードは行わず、フォーマッターをキャッシュし、AsyncImageまたはキャッシュ画像パイプラインを使用します。
  • InstrumentsのSwiftUIテンプレートで検証します。スクロール中のview-body評価回数を確認します。無関係な状態が変更されたときにbodyが評価される行タイプは、状態所有権のバグです。ステップ2を修正し、その周りをメモ化しないでください。

ステップ5: 状態からのアニメーション

  • 状態からアニメーションを駆動します:withAnimation { model.expanded.toggle() }。
  • 暗黙的なグローバルアニメーションよりも、特定の値にスコープされた.animation(_:value:)を優先します。暗黙的なアニメーションは意図しないものをアニメーション化します。
  • 共有要素トランジションにはmatchedGeometryEffectを、挿入/削除にはtransitionを使用します。
  • accessibilityReduceMotionを尊重します。設定されている場合は、移動を透明度フェードに置き換えます。

ステップ6: アクセシビリティパス

  • accessibilityLabel/accessibilityValueを追加します。関連する要素をaccessibilityElement(children: .combine)でグループ化し、行が5つの断片ではなく1つの文として読み上げられるようにします。
  • Dynamic Typeを尊重します。システムテキストスタイルを使用し、テキストをクリップする固定フレームは避けます。最大のアクセシビリティサイズで検証します。
  • コントラストを確認し、ダークモード、大規模Dynamic Type、空/読み込み中/エラー状態の#Previewバリアントをサンプルデータとともに追加します。

成果物:状態所有権、悪い例と良い例

悪い例 - 検索テキストがツリー全体が監視するモデルにあり、行がストア全体を受け取るため、キー入力のたびに画面全体が無効化されます。

@Observable final class ScreenStore {
  var searchText = ""
  var items: [Item] = []
}

struct ContactList: View {
  @State private var store = ScreenStore()
  var body: some View {
    VStack {
      TextField("Search", text: $store.searchText)
      ForEach(store.items) { item in
        ContactRow(store: store, item: item) // 行はすべてを監視
      }
    }
  }
}

良い例 - 検索テキストはビューローカルであり、行は読み取る値のみを取得し、リストは安定したIDで遅延ロードされます。

struct ContactList: View {
  @State private var searchText = ""
  @Environment(ContactModel.self) private var model
  var body: some View {
    List(model.filtered(searchText)) { item in
      ContactRow(name: item.name, isOnline: item.isOnline)
    }
    .searchable(text: $searchText)
  }
}

struct ContactRow: View {
  let name: String
  let isOnline: Bool
  var body: some View {
    Label(name, systemImage: isOnline ? "circle.fill" : "circle")
  }
}

良いバージョンでの入力は、Listコンテンツクロージャとフィルタリングされたメンバーシップが変更された行のみを無効化します。それ以外は無効化されません。

成果物

動作するSwiftUIビューコードと、状態の各ピースについてその所有者、ラッパー、読み取り/書き込みを行うビューを記載した1段落の状態マップを作成します。レビューの場合は、フレーム予算への影響順に並べられた、各修正を含む所見リストを作成します。

禁止事項

  • body評価中に状態を変更しないでください。ループしたり、未定義動作の警告がトリガーされます。
  • onAppearで生のTaskを使用して非同期処理を行わないでください。.task {}を使用してください。これは非表示時に自動的にキャンセルされます。
  • モデルにビュータイプ(Color、Image、AnyView)を入れないでください。モデルはUIなしでテスト可能である必要があります。
  • 「シンプルさのために」すべての状態を1つの画面レベルのストアに持ち上げないでください。それはまさに、キー入力のたびに画面を再描画させるパターンです。
  • 所有権を修正する前にequatable()やキャッシュで無効化バグを隠蔽しないでください。バグは同じオブジェクトを監視する次のビューで再発します。
  • テキストに固定フレームを使用しないでください。Dynamic Typeでクリップされます。

品質基準

完成したビューは以下の条件を満たす必要があります。

  • 状態の各ピースには正確に1つの所有者があり、機能する最も狭いラッパーが使用されている。
  • Instrumentsが、行のbodyが自身のデータが変更された場合にのみ評価されることを示す。
  • 予想される最大のリストのスクロールが、ベースラインの60Hzデバイスでフレーム予算を維持する。
  • 長寿命の状態は、非表示になる可能性のあるビューの上に持ち上げられ、ナビゲーション後も存続する。
  • キーボード回避とセーフエリアが処理されている(safeAreaInset、scrollDismissesKeyboard)。
  • VoiceOverが各インタラクティブ要素を意味のあるラベルで読み上げ、レイアウトが最大のDynamic Typeサイズでも耐え、reduceMotionが尊重されている。
  • 読み込み中、空、エラー、ダークモード、大規模テキスト状態のプレビューが存在する。

単一画面を超えたアプリ全体のプロファイリングについては、mobile-perf-profilerと連携してください。

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

SkillMedev/skills

Designs REST API surfaces - resource naming, HTTP method and status-code semantics, error shapes, pagination, and filtering - and delivers an endpoint spec a consumer can build against without asking questions. Use when someone asks "how should I name this endpoint", "what status code should this return", "should this be PUT or PATCH", "how do I paginate this list", or is reviewing an API before it ships to external consumers. Do NOT use for planning breaking-change rollouts and deprecation windows - use api-versioning-strategist instead; for GraphQL type and resolver design - use graphql-schema instead; for generating client SDKs from an existing spec - use api-client-generator instead; for designing inbound webhook endpoints - use webhook-receiver-hardener instead.

SkillMedev/skills

Produce an accurate, properly timed caption track (SRT or WebVTT) from a video's audio - transcribing or aligning to the voiceover script, timing cues to speech, and enforcing line-length and reading-speed rules so captions are readable and in sync. Use when someone says "generate captions", "make subtitles from the audio", "transcribe and caption this", "export an SRT or VTT", "the captions are out of sync", or "the subtitles flash by too fast to read". Do NOT use to burn-in, style, reframe, or position an existing caption track for a platform (9:16, brand styling, safe areas) - that is social-video-formatter; do NOT use to animate text word-by-word as a motion graphic - that is kinetic-typography; do NOT use to write the spoken script in the first place - that is narration-script.

SkillMedev/skills

Turns data and charts into a decision-driving narrative structured as headline finding, trend, implication, and recommended action - with finding-led chart titles, context for every number, annotation guidance, and honest flags on any conclusion the data cannot support. Use when someone says "turn these numbers into a story", "what's the takeaway from this data", "help me present these results to leadership", or has charts but no narrative. Do NOT use for compressing a long document into a one-pager - use executive-summary instead - or for running the analysis that produces the findings - use eda-playbook instead.

SkillMedev/skills

Use when a task needs live or historical money data - "convert USD to EUR", "current/past exchange rate", "FX rate on this date / over this range", or "current price of Bitcoin/Ethereum, market cap, 24h change". Frankfurter (ECB reference rates, no key) is the FX default; CoinGecko's free keyless tier covers crypto. Do NOT use for stock quotes or equities - no keyless stock API survives verification, say so instead of guessing; do NOT use for country economic indicators like GDP or inflation series - use government-open-data instead; if the request is a vague "I need live data", route through public-data-api-picker.

SkillMedev/skills

Builds a driver-based FP&A operating model linking business inputs to P&L, balance sheet, and cash flow outputs. Use when building an annual plan, preparing investor materials, running scenario analysis, or stress-testing the business.

SkillMedev/skills

Use when a task needs live geographic lookups - "geocode this address", "what's at these coordinates" (reverse geocoding), "lat/lon for this city", "which country/state is this ZIP or postal code in", or "country facts: capital, currency, population, flag". Nominatim (OpenStreetMap) is the geocoding default; Zippopotam for postal codes; APICountries for country facts. All keyless. Do NOT use for weather at a location - use weather-climate instead; do NOT use for country-level statistics over time (GDP, population trends) - use government-open-data instead; if the request is a vague "I need live data", route through public-data-api-picker.

SkillMedev/skills

Runs the full Getting Things Done loop - capture, clarify, organize, reflect, engage - building a trusted system of context lists, a projects list with defined next actions, and a weekly review habit. Use when someone says "I'm overwhelmed and things are slipping through the cracks", "set up GTD for me", "help me do a brain dump and organize it", or "my to-do list is a mess". Do NOT use for just running the weekly review ritual itself - use weekly-review instead - or for clearing an email backlog - use inbox-zero.

SkillMedev/skills

Processes any email backlog to zero using the 4Ds - Delete, Delegate, Defer, Do - with a mass-archive strategy for the obvious, a touch-each-email-once discipline, and a keep-it-clear system of batched processing windows, ruthless unsubscribing, filters, and a minimal folder setup. Use when someone says "I have 5,000 unread emails", "help me get to inbox zero", "email is eating my whole day", or treats their inbox as a to-do list. Do NOT use for drafting the reply emails themselves or prioritization rules for an ongoing support queue - use email-triage instead - or for protecting focus time around the email windows - use deep-work-planner instead.

SkillMedev/skills

Write landing-page copy section by section - hero, social proof, features-as-benefits, objections, CTA - leading with one promise and proving it down the page. Use when someone asks "write my landing page", "improve my hero headline", "what should the homepage say", "turn these features into benefits", or is shipping a new page for a launch or campaign. Do NOT use for testing and optimizing an existing page's conversion rate - use landing-page-cro instead; for the one-line claim itself use positioning-statement; for the full message ladder use messaging-hierarchy.

SkillMedev/skills

Improves an existing landing page's conversion rate through evidence-first CRO - audit heatmaps and recordings, write structured hypotheses, prioritize with ICE scoring, and run one-variable tests to statistical significance. Use when someone asks "why isn't my landing page converting", "audit this page before we scale spend", "which A/B test should we run first", or after a CVR drop or ahead of a paid-traffic push. Do NOT use for writing a new landing page from scratch - use landing-page-copy instead. Do NOT use for auditing the ad accounts sending the traffic - use paid-acquisition-audit instead. Do NOT use for reading the results of a finished experiment - use ab-test-analyzer instead.

SkillMedev/skills

Runs structured coaching sessions using values clarification and the GROW model, ending every session with one committed action, a deadline, and an if-then plan for the likely obstacle. Use when someone says "I feel stuck in my life", "help me figure out what I want", "hold me accountable to my goals", or "coach me through this decision". Do NOT use for building a stress toolkit - use stress-management instead - or a journaling practice - use journal-framework; for a standing goal-tracking system, use goals-accountability. Coaching, not therapy: signs of clinical distress route to a licensed professional.

SkillMedev/skills

Adapts English content for a target language and region - swapping idioms, setting the right formality register, replacing cultural references, converting dates, units, and currency - and delivers the localized text with a notes column explaining each adaptation and flagging what needs a native reviewer. Use when someone asks "localize this copy for the Japanese market", "adapt our marketing copy for the Mexican market", "make this translation sound native instead of literal", or a literal translation reads foreign, stiff, or risky. Do NOT use for auditing in-product UI text quality - use ux-writing-audit instead.

SkillMedev/skills

Turns a natural-language video brief into a complete, ready-to-preview Remotion composition - extracts duration, scenes, brand colors, aspect ratio, and real copy; plans the frame budget; and writes data-driven React/TypeScript using useCurrentFrame, interpolate, spring, AbsoluteFill, and Sequence, registered in Root.tsx. Use when someone says "build a 20-second product demo video", "animate a feature walkthrough", "write the Remotion code for this marketing clip", or wants a scene-by-scene composition they can scrub in Studio. Do NOT use for rendering, iterating, or batching the finished MP4 - use remotion-render instead - or for installing and scaffolding the project - use remotion-setup instead.

SkillMedev/skills

Scaffolds a new Remotion video project wired for Claude Code Agent Skills - Node check, create-video scaffold, skills install, folder conventions, Google Fonts, and a smoke-test render. Use whenever someone wants to start making videos with Remotion and Claude, even just "make product videos with Claude.

SkillMedev/skills

Classifies incident severity (SEV1-4) using impact, scope, and urgency signals and decides who to page. Use when an alert fires or a report comes in and a severity call must be made quickly.

SkillMedev/skills

Use the Skill Me catalog from inside any conversation - discover, install, and manage Claude skills through the Skill Me MCP, and load installed skills automatically each session.

SkillMedev/skills

Write one platform-native caption from a topic and brand voice, with a front-loaded hook, native length, and a single earned CTA. Use when the user gives a topic (and optionally brand voice or a described image/video) and asks for an Instagram, LinkedIn, X/Twitter, or TikTok caption. Do NOT use when the user wants a dedicated standalone LinkedIn post - use linkedin-post-writer instead; or a multi-post X thread - use tweet-thread-builder instead; or to adapt one existing piece of content into versions for several channels - use cross-platform-reformatter instead.

SkillMedev/skills

Reframe and export a finished video for social platforms - 9:16 ↔ 16:9 cropping, burned-in captions, a platform-native first frame, loop design, and per-platform specs (aspect, length, safe areas) for TikTok, Reels, Shorts, X, and LinkedIn. Use when someone says "make this vertical", "crop to 9:16", "format for TikTok/Reels/Shorts", "add captions/subtitles", "why is my video cut off on mobile", "resize for Instagram", or "export for social". Do NOT use when the question is about the storyboard or shot order before any video exists (use video-storyboard); the animation craft of how elements move (use motion-design-principles); animated word-by-word caption styling (use kinetic-typography); palette, contrast, or lighting (use motion-color-and-light); directing the product-demo content and screen choreography (use product-demo-director); or scoring, beat-syncing, or audio (use sound-and-music-sync) - this is the craft layer that decides WHAT to format for the feed, then hands a concrete spec to remotion-compo...

SkillMedev/skills

Writes and tunes PySpark jobs - join strategy and broadcast size limits, shuffle-partition sizing, skew diagnosis and salting, UDF avoidance, caching, and output file layout - with concrete size and skew thresholds. Use when someone asks "why is my Spark job slow", "should I broadcast this join", "one task takes forever while the rest finish", "my job OOMs during a join", or is writing a new PySpark ETL job. Do NOT use for Kafka topic, consumer-group, or streaming-pipeline design - use kafka-pipelines instead; do NOT use for single-machine dataframe work that fits in memory - use pandas-expert instead.

関連スキル