⚠️ Try not to use already used names like Data
for your internal module. I will use MyEnum
instead in this answer
When something conforms to Identifiable
, it must return something that can be identified by that. So you should return something unique to that case. For String
base enum
, rawValue
is the best option you have:
extension MyEnum: Identifiable {
var id: RawValue { rawValue }
}
Also, enum
s can usually be identified by their selves:
extension MyEnum: Identifiable {
var id: Self { self }
}
⚠️ Note 1: If you return something that is unstable, like UUID() or an index, this means you get a new object each time you get the object and this will kill reusability and can cause epic memory and layout process usage beside view management issues like transition management and etc.
Take a look at this weird animation for adding a new pet:
Note 2: From Swift 5.1, single-line closures don’t need the return
keyword.
Note 3: Try not to use globally known names like Data
for your own types. At least use namespace for that like MyCustomNameSpace.Data
Inline mode
You can make any collection iterable inline by one of it’s element’s keypath:
For example to self
:
List(MyEnum.allCases, id:\.self)
or to any other compatible keypath:
List(MyEnum.allCases, id:\.rawValue)
✅ The checklist of the identifier: (from WWDC21)
- Exercise caution with random identifiers.
- Use stable identifiers.
- Ensure the uniqueness, one identifier per item.