LoginSignup
26
6

More than 3 years have passed since last update.

SwiftUI: ListとIdentifiableについて

Last updated at Posted at 2020-01-01

はじめに

今回はListとIdentifiableプロトコルを実装した構造体を利用してUITableViewみたいなものを簡単に作りたいと思います! UIKitよりSwiftUIの方がかなりシンプルにかけるので、その違いを意識してみるといいかもしれません笑
※勉強中のため、正しい説明になっていないかもしれません。予めご了承いただければと思います、、、

環境

  • macOS Catalina(10.15.2)
  • xcode(11.3)
  • Swift5.1
  • SwiftUI

こんな感じです

Listスクリーンショット 2020-01-01 20.18.31.png
ContentView.swift

import SwiftUI

struct Hyoka: Identifiable {
    var id = UUID()
    var name: String
}

struct ContentView: View {

    var body: some View {
        let hyokas = [Hyoka(name: "氷菓"),
                      Hyoka(name: "愚者のエンドロール"),
                      Hyoka(name: "クドリャフカの順番"),
                      Hyoka(name: "遠回りする雛"),
                      Hyoka(name: "ふたりの距離の概算"),
                      Hyoka(name: "いまさら翼といわれても")]

        return List(hyokas) { hyoka in
            Text(hyoka.name)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

解説

今回のポイントはHyoka構造体にIdentifiableプロトコルを実装していると言う点です。Identifiableプロトコルの中身は、

public protocol Identifiable {

    /// A type representing the stable identity of the entity associated with `self`.
    associatedtype ID : Hashable

    /// The stable identity of the entity associated with `self`.
    var id: Self.ID { get }
}

となっており、Hyoka構造体はidをプロパティとして定義する必要があります。idの中身はUUID構造体
を利用しており一意なInt型の値が入っています。(自分でidを入れても構わないです。)

このようにすればListができるのですが、なぜそもそも一意のidを付与しなければならないのか??についてもう少し説明を加えます。
その答えはずばり、SwiftUI側がそのViewで利用されているデータがどれなのかを特定しておかないと、データが更新されたときにどのViewを再構築すればいいのかわからなくなってしまうからです。今回の場合、SwiftUI側がTextビューそれぞれのデータを区別したいので予めidを割り振る必要があります。

参考

26
6
1

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
26
6