Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Initialzier requires String conform to Identifiable

Tags:

swift

swiftui

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?

like image 679
ShedSports Avatar asked Sep 01 '25 01:09

ShedSports


2 Answers

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.

like image 155
vadian Avatar answered Sep 02 '25 19:09

vadian


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

like image 38
Josh Avatar answered Sep 02 '25 19:09

Josh