Fixing the ForEach requires that T conform to Identifiable error in Swift
The actual error message is too long for an article title. The error message looks like the following:
Error: Referencing initializer ‘init (_:content:)’ on ‘ForEach’ requires that ‘T’ conform to ’Identifiable’
Where T
is a struct or class.
Why am I getting this error?
You have a ForEach block that does not uniquely identify each item. The compiler needs a way to uniquely identify each item in the ForEach block. If you do not provide a way to uniquely identify the items, you get the error.
The most common cause of the error is the only argument you supplied to the ForEach is the collection of items, and the item’s struct or class does not conform to the Identifiable
protocol.
ForEach(items) { item in
}
Ways to fix the error
The easiest way to fix the error is to provide an id
argument to the ForEach and using \.self
as the value.
ForEach(items, id: \.self) { item in
}
Another way to fix the error is to make the struct or class of the items in the ForEach conform to the Identifiable
protocol. Add an id
property to the struct or class that uniquely identifies each instance of the struct or class.
struct MyStruct: Identifiable {
let id = UUID()
}
The call to UUID
creates a unique identifier for each instance of the struct your app creates.