3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIのIdentityについて

Last updated at Posted at 2025-12-10

SwiftUI とは

  • Appleが提供する宣言型UIフレームワークで、コードベースで直感的にUIを構築できます

命令型UI

  • 命令型プログラミングの例: 「Rufus 来なさい。Rufus バットを持ちなさい。Rufus 打席について。」のように、各手順を詳細に指示する

宣言型UI

  • 「Rufusにホームランを打ってほしい」と、「起こってほしいこと」つまり期待される「結果」を記述する
  • 状態の変更を自動で検知しUIが変化するイメージ

ViewのIdentityついて

例として文字を表示する Text("hoge")Text("hoge") の違いを考えます。
人間から見ると同じ文字で構成された同じViewのように見えます。しかし、機械的にはこの2つのViewを 異なるもの として処理を進める必要があります。ここで Viewを識別するために使われるのが Identity です。Identity はViewの識別だけではなくレンダリングにも関係している重要な技術です。

  • dentityが同一であれば同じView、異なれば違うViewと判断される。

    • Explicit identity - カスタムまたはデータで決まる識別子(明示的に指定)
    • Structural identity - Viewの型と階層内の位置によって決まる識別子(暗黙的に指定)
  • Explicit identity 

    • id を明示的に付与する。この id によってViewを識別している。
hoge.swift
// case1
ForEach(..., id: \.someProperty) { ... }

// case2
VIew.id("identifier")
VIew.id(1)
  • Structural identity
    • id が暗黙的に付与される
hoge.swift
var body: some View {
  // if 文で画面が切り替わると、都度画面が破棄される。
  if condition {
      viewA
    } else {
      viewB
    }
  }
}

レンダリングする時、意図しない画面更新が行われた場合は Identity を分析すると何かヒントが見つかるかも知れません。では、良いSwiftUIライフを

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?