swiftui

Simple SwiftUI List example. What am I doing wrong?


I'm having problems binding string data to a a Text inside a list. Not sure exactly what I am doing wrong.

enter image description here


Solution

  • It's a simple fix. When you pass an array to List, the elements in the array need to conform to the Identifiable protocol. String does not conform to Identifiable, so the way to make this work is to use .identified(by:) like so:

    struct StringList: View {
        let strings = ["1234", "5678"]
    
        var body: some View {
            List(strings.identified(by: \.self)) { string in
                Text(string)
            }
        }
    }
    

    You can also use a ForEach inside List:

    struct StringList: View {
        let strings = ["1234", "5678"]
    
        var body: some View {
            List {
                ForEach(strings.identified(by: \.self)) { string in
                    Text(string)
                }
            }
        }
    }
    

    Both of these examples achieve the same output, but the first one is cleaner and requires less code.

    Update

    As of Xcode Beta 4, identified(by:) has been deprecated in favor of specific initializers for List and ForEach:

    struct StringList: View {
        let strings = ["1234", "5678"]
    
        var body: some View {
            List(strings, id: \.self) { string in
                Text(string)
            }
        }
    }
    
    struct StringList: View {
        let strings = ["1234", "5678"]
    
        var body: some View {
            List {
                ForEach(strings, id: \.self) { string in
                    Text(string)
                }
            }
        }
    }