美文网首页
SwiftUI 基础之 Identifiable

SwiftUI 基础之 Identifiable

作者: 雪碧童鞋 | 来源:发表于2020-03-15 13:58 被阅读0次

Identifiable 在apple文档中解释的比较晦涩:

//A class of types whose instances hold the value of an entity with stable identity.
一类类型,其实例持有具有稳定标识的实体的值.

public protocol Identifiable {
    associatedtype ID : Hashable
    var id: Self.ID { get }
}

其实Identifiable 非常简单实用,主要作用就是作为一个对象的唯一标识。

来个demo

一个 Expense类

struct ExpenseItem {
    let id:  UUID()
    let name: String
    let type: String
    let amount: Int
}

我们遍历他,需要一个唯一标识

ForEach(expenses.items, id: \.id) { item in
    Text(item.name)
}

我们实用Identifiable就不用这么麻烦了

struct ExpenseItem: Identifiable {
    let id = UUID()
    let name: String
    let type: String
    let amount: Int
}
ForEach(expenses.items) { item in
    Text(item.name)
}

参考:Working with Identifiable items in SwiftUI

相关文章

网友评论

      本文标题:SwiftUI 基础之 Identifiable

      本文链接:https://www.haomeiwen.com/subject/lejlehtx.html