Instance method 'appendInterpolation(_:formatter:)' requires that 'Any' inherit from 'NSObject'

Viewed 4897

I have an array of dictionaries. However I want to display a specific key from the dictionary to a text. But I keep getting the error "Instance method 'appendInterpolation(_:formatter:)' requires that 'Any' inherit from 'NSObject'"

Here is my dictionary

[
["nickname":"Spurs","Pts":21],
["nickname":"Liverpool","Pts":20]
]

Here is the code to print out the array

struct TeamList: View {
    var clubRanking: [[String:Any]] = [["nickname":"Spurs","Pts":21],["nickname":"Liverpool","Pts":20]]
    var body: some View {
        VStack(alignment: .leading) {
            Text("\(clubRanking[0]["nickname"])")      //The error happens here
        }
    }
}

struct TeamList_Previews: PreviewProvider {
    static var previews: some View {
        TeamList()
    }
}
1 Answers

Don't use [String:Any] to store your data models. Create a proper model type and store an Array of that type.

struct ClubRanking {
    let nickName: String
    let points: Int
}

struct TeamList: View {
    let rankings = [ClubRanking(nickName: "Spurs", points: 21), ClubRanking(nickName: "Liverpool", points: 20)]
    var body: some View {
        VStack(alignment: .leading) {
            Text("\(rankings[0].nickName)")
        }
    }
}

If you want to display the full rankings, you can also make ClubRanking conform to CustomStringConvertible and display the description property of each element of rankings in a ForEach.

extension ClubRanking: CustomStringConvertible {
    var description: String {
        "Team: \(nickName), points: \(points)"
    }
}

struct TeamList: View {
    let rankings = [ClubRanking(nickName: "Spurs", points: 21), ClubRanking(nickName: "Liverpool", points: 20)]
    var body: some View {
        VStack(alignment: .leading) {
            ForEach(rankings, id: \.nickName) { ranking in
                Text(ranking.description)
            }
        }
    }
}
Related