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.
1 2 3 4 |
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.
1 2 3 4 |
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
1 2 3 4 |
struct MyStruct: Identifiable { let id = UUID() } |
The call to UUID
creates a unique identifier for each instance of the struct your app creates.
Do you want to learn how to fix errors in your Swift code?
I’m writing a book, Fixing Swift Code, that will teach you how to find and fix errors in your Swift code so your projects will build successfully and run without crashing. Some of the things you’ll learn in the book include the following:
- What Xcode’s build error messages really mean
- How to fix your code so your project builds
- How to find where your app crashes
- The most common causes of app crashes and how to fix them
You can learn more about the book and get a discount on the book when it ships by going to the book’s homepage.