SwiftUI ForEach 'identified(by:)' is depre

2020-08-26 14:32发布

On XCode 11 beta 4 the following seems to be deprecated and I don't know how to rewrite this. Does anybody know how to use 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))

        }
}

标签: swiftui
3条回答
疯言疯语
2楼-- · 2020-08-26 14:56

If your list objects conform to the identifiable protocol & do have id (uniquely defined) variable inside along with other properties of an object.

You can simply iterate over the list by not passing the id: parameters.

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

Otherwise, You can simply iterate using ForEach:

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

Checkout Few Reference Doc: Identifiable Documentation

查看更多
Summer. ? 凉城
3楼-- · 2020-08-26 15:13

(Still working with Xcode 11.0 / Swift 5.1)

I haven't downloaded Xcode Beta 4 yet, but according to the documentation, it should be something like:

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

You can also use a struct that conforms to Identifiable (note that this won't work on tuple because you can't add protocol conformance):

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))
}
查看更多
再贱就再见
4楼-- · 2020-08-26 15:14

Adding example for list

List(showTargets, id: \.id) { item in
     ItemRow(item: item)
 }

when showTargets conforms to identifiable protocol:

List(showTargets) { item in
     ItemRow(item: item)
 }
查看更多
登录 后发表回答