30
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Identifiable ってなんぞ?

Last updated at Posted at 2019-11-11

経緯

とりあえず雰囲気で List を作る

struct ContentView: View {
    let users = ["sato", "suzuki", "watanabe"]

    var body: some View {
        List(users){ user in
            Text(user)
        }
    }
}

怒られた。
スクリーンショット 2019-11-11 11.09.35.png

Initializer 'init(_:rowContent:)' requires that 'String' conform to 'Identifiable'
→ 初期化子 'init(_:rowContent :)'では、 'String'が 'Identifiable'に準拠している必要があります

Identifiable ってなんぞ?

@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
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 }
}

##id という変数を持っていることを示すプロトコル

id という変数を持った struct を作成して Identifiable に準拠させる

struct User: Identifiable {
    var id: String
    var name: String
}

ContentView を書き換える

struct ContentView: View {
    let users = [
        User(id: "001", name: "sato"),
        User(id: "002", name: "suzuki"),
        User(id: "003", name: "watanabe")
    ]

    var body: some View {
        List(users){ user in
            Text(user.name)
        }
    }
}

これでエラーが消えました。

30
16
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
30
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?