Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI ForEach 'identified(by:)' is deprecated. Use ForEach(_:id:) or List(_:id:)

Tags:

swiftui

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))

        }
}
like image 607
krjw Avatar asked Jul 19 '19 09:07

krjw


People also ask

What is ID in foreach SwiftUI?

The id: \. self part is required so that SwiftUI can identify each element in the array uniquely – it means that if you add or remove an item, SwiftUI knows exactly which one. You can use this approach to create loops of any type.

What is foreach in Swift?

Calls the given closure on each element in the sequence in the same order as a for - in loop.

What does id self Mean Swift?

id: . self tells Swift to use as unique id (keypath) the hash of the object. It explains why the name "self" is used. id: . self is especially useful for the basic Swift types like Integer and String.


2 Answers

(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))
}
like image 81
rraphael Avatar answered Sep 19 '22 21:09

rraphael


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)
 }
like image 33
patilh Avatar answered Sep 18 '22 21:09

patilh