gpt4 book ai didi

ios - 实例方法 'appendInterpolation(_:formatter:)'要求 'Any'继承自 'NSObject'

转载 作者:行者123 更新时间:2023-12-05 06:08:17 28 4
gpt4 key购买 nike

我有一系列字典。但是我想将字典中的特定键显示为文本。但我不断收到错误消息“实例方法‘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()
}
}

最佳答案

不要使用[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,显示每个元素的description属性在 ForEach 中的 rankings

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

关于ios - 实例方法 'appendInterpolation(_:formatter:)'要求 'Any'继承自 'NSObject',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65144249/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com