SwiftUI 基础之 Identifiable

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容