I am attempting writing some SwiftUI code for the very first time and am running into an issue while trying to make a simple table view. In this code teams
is an array of String
, but the List
is giving me the following error:
Initializer 'init(_:rowContent:)' requires that 'String' conform to 'Identifiable'
var body: some View {
let teams = getTeams()
Text("Hello there")
List(teams) { team in
}
}
Anyone have an idea what it means?
The argument of List
is required to be unique, that's the purpose of the Identifiable
protocol
You can do
List(teams, id: \.self) { team in
but then you are responsible to ensure that the strings are unique. If not you will get unexpected behavior.
Better is to use a custom struct with an unique id
conforming to Identifiable
for example
struct Team: Identifiable {
let id = UUID()
let name: String
}
Then you can use your syntax as-is.
The Apple preferred way to do this is to add a String extension:
extension String: Identifiable {
public typealias ID = Int
public var id: Int {
return hash
}
}
See this code sample for reference: https://github.com/apple/cloudkit-sample-queries/blob/main/Queries/ContentView.swift
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With