gpt4 book ai didi

ios - Swift:JSON 意外错误,二级元素为零

转载 作者:行者123 更新时间:2023-11-28 10:23:11 25 4
gpt4 key购买 nike

我在尝试创建 JSON 对象时遇到问题。一切都很好,直到我尝试创建一个具有 nil 值的二级元素:

var json = [String: AnyObject]()
json["id"] = 1234567

let secondLevel : [String: AnyObject] = ["i1": 12, "i2": "not nil"]
json["secondLevel"] = secondLevel

这很好,但如果我尝试:

let secondLevel : [String: AnyObject?] = ["i1": 12, "i2": nil]
json["secondLevel"] = secondLevel

我收到以下错误:

cannot assign a value of type '[String : AnyObject?]' to a value of type 'AnyObject?'

这是什么意思? [String:AnyObject?] 不是 AnyObject 类型吗?

我该怎么做才能避免这个错误?

最佳答案

您可以使用 Any 而不是 AnyObject

Type Casting for Any and AnyObject

Swift provides two special type aliases for working with non-specific types:

AnyObject can represent an instance of any class type.Any can represent an instance of any type at all, apart from function types.

NOTE:Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.

来自 The Swift Programming Language

var json = [String: Any]()
json["id"] = 123452

let secondLevel : [String: Any?] = ["i1": 12, "i2": nil]
json["secondLevel"] = secondLevel

print(json)

关于ios - Swift:JSON 意外错误,二级元素为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31427537/

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