ios 示例方法“appendInterpolation(_:formatter:)”要求“Any”继承自“NSObject”

6gpjuf90  于 2023-03-05  发布在  iOS
关注(0)|答案(2)|浏览(162)

我有一个字典数组。但是我想将字典中的特定键显示为文本。但是我一直收到错误“示例方法'appendInterpolation(_:formatter:)'要求'Any'继承自'NSObject'”
这是我的字典

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

下面是输出数组的代码

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()
    }
}
bvuwiixz

bvuwiixz1#

不要使用[String:Any]来存储你的数据模型,创建一个合适的模型类型并存储一个该类型的Array

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)")
        }
    }
}

如果你想显示完整的排名,你也可以让ClubRanking符合CustomStringConvertible,并在一个ForEach中显示rankings的每个元素的description属性。

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)
            }
        }
    }
}
quhf5bfb

quhf5bfb2#

这里的问题是示例方法“appendInterpolation(_:formatter:)”要求“Any”从“NSObject”继承
要解决这个问题,我们需要将类型转换(类型转换意味着将一种数据类型更改为另一种数据类型)为String
struct俱乐部排名{让昵称:字符串字母点:整数}
结构团队列表:查看{让排名= [俱乐部排名(昵称:“马刺”,积分:21)、俱乐部排名(昵称:“利物浦”,积分:20)]变量主体:一些视图{ ForEach(排名,id:.昵称){ each in if let rank = each[“points”] as?String { Text(“(rank)”)} } }

相关问题