gpt4 book ai didi

SwiftUI ForEach 'identified(by:)' 已弃用。使用 ForEach(_ :id:) or List(_:id:)

转载 作者:行者123 更新时间:2023-12-02 16:19:39 24 4
gpt4 key购买 nike

在 XCode 11 beta 4 上,以下内容似乎已被弃用,我不知道如何重写它。有人知道如何使用 ForEach(_:id:) 吗?

@State private var showTargets = [
(id: 1, state: false, x: 109.28, y: 109.28),
(id: 2, state: false, x: 683, y: 109.28),
(id: 3, state: false, x: 1256.72, y: 109.28)
]

...

var body: some View {
HStack {

ForEach(showTargets.identified(by: \.id)) { item in
Text(String(item.x))

}
}

最佳答案

(仍可使用 Xcode 11.0/Swift 5.1)

我还没有下载 Xcode Beta 4,但是根据documentation ,它应该是这样的:

ForEach(showTargets, id: \.id) { item in
Text(String(item.x))
}

您还可以使用符合可识别struct(请注意,这不适用于元组,因为您无法添加协议(protocol)一致性):

struct Targets: Identifiable {
var id: Int
var state: Bool
var x: Double
var y: Double
}

let showTargets = [
Targets(id: 1, state: false, x: 109.28, y: 109.28),
Targets(id: 2, state: false, x: 683, y: 109.28),
Targets(id: 3, state: false, x: 1256.72, y: 109.28)
]

ForEach(showTargets) { item in
Text(String(item.x))
}

关于SwiftUI ForEach 'identified(by:)' 已弃用。使用 ForEach(_ :id:) or List(_:id:),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57109557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com