3

我在 Swift 中创建了一个字典:

var type:String
var content:[UInt8]
let dict = NSMutableDictionary()
dict.setValue(type, forKey: "type")
dict.setValue(content, forKey: "content")

我收到一个错误:Cannot convert value of type [UInt8] to expected argument type 'AnyObject?',但如果我将内容类型更改为[UInt],它将正常工作。为什么?

实际上,我想像在 Java 中一样定义一个字节数组,所以我想使用[UInt8],有人可以帮助我吗?

4

1 回答 1

4

你可以使用 Swift 原生类型

var dict: Dictionary<String,Array<UInt8>> = [:]
dict["first"]=[1,2,3]
print(dict) // ["first": [1, 2, 3]]

我建议您尽可能多地使用原生 Swift 类型...请参阅 Martins 对您的问题的注释,它非常有用!

如果情况是您想在那里存储任何值,只需将您的字典定义为正确的类型

var dict: Dictionary<String,Array<Any>> = [:]
dict["first"]=[1,2,3]
class C {
}
dict["second"] = ["alfa", Int(1), UInt(1), C()]
print(dict) // ["first": [1, 2, 3], "second": ["alfa", 1, 1, C]]

看,值的类型仍然是众所周知的,你可以检查一下

dict["second"]?.forEach({ (element) -> () in
    print(element, element.dynamicType)
})

/*
alfa String
1 Int
1 UInt
C C
*/

如果你想存储任何值,你可以自由地做......

var type:String = "test"
var content:[UInt8] = [1,2,3,4]
var dict: Dictionary<String,Any> = [:]
dict["type"] = type
dict["content"] = content
dict.forEach { (element) -> () in // ["content": [1, 2, 3, 4], "type": "test"]
    print("key:", element.0, "value:", element.1, "with type:", element.1.dynamicType)
    /*
    key: content value: [1, 2, 3, 4] with type: Array<UInt8>
    key: type value: test with type: String
    */
}
于 2015-12-11T07:09:22.873 回答