实例方法 'appendInterpolation(_:formatter:)' 要求 'Any' 继承自 'NSObject'
Posted
技术标签:
【中文标题】实例方法 \'appendInterpolation(_:formatter:)\' 要求 \'Any\' 继承自 \'NSObject\'【英文标题】:Instance method 'appendInterpolation(_:formatter:)' requires that 'Any' inherit from 'NSObject'实例方法 'appendInterpolation(_:formatter:)' 要求 'Any' 继承自 'NSObject' 【发布时间】:2020-12-04 13:16:06 【问题描述】:我有一个字典数组。但是我想将字典中的特定键显示为文本。但我不断收到错误“实例方法 '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()
【问题讨论】:
【参考方案1】:不要使用[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)
【讨论】:
以上是关于实例方法 'appendInterpolation(_:formatter:)' 要求 'Any' 继承自 'NSObject'的主要内容,如果未能解决你的问题,请参考以下文章