Ios Swift dictionary将[UInt8]作为值放置不起作用

Ios Swift dictionary将[UInt8]作为值放置不起作用,ios,arrays,swift,uint,Ios,Arrays,Swift,Uint,我用Swift创建了一本词典: var type:String var content:[UInt8] let dict = NSMutableDictionary() dict.setValue(type, forKey: "type") dict.setValue(content, forKey: "content") 我得到一个错误:无法将[UInt8]类型的值转换为预期的参数类型“AnyObject?”,但是如果我将内容类型更改为[UInt],它将正常工作。为什么? 事实上,我想在Ja

我用Swift创建了一本词典:

var type:String
var content:[UInt8]
let dict = NSMutableDictionary()
dict.setValue(type, forKey: "type")
dict.setValue(content, forKey: "content")
我得到一个错误:
无法将[UInt8]类型的值转换为预期的参数类型“AnyObject?”
,但是如果我将内容类型更改为
[UInt]
,它将正常工作。为什么?


事实上,我想在Java中定义一个字节数组,所以我想使用
[UInt8]
,任何人都可以帮助我?

您可以使用Swift本机类型

var dict: Dictionary<String,Array<UInt8>> = [:]
dict["first"]=[1,2,3]
print(dict) // ["first": [1, 2, 3]]
如果你想储存任何价值,你可以自由地储存

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
    */
}
var类型:String=“test”
变量内容:[UInt8]=[1,2,3,4]
变量dict:Dictionary=[:]
dict[“type”]=类型
dict[“content”]=内容
dict.forEach{(element)->()在//[“content”:[1,2,3,4],“type”:“test”]
打印(“键:”,元素.0,“值:”,元素.1,“类型:”,元素.1.dynamicType)
/*
关键字:内容值:[1,2,3,4],类型:数组
键:类型值:使用类型:字符串进行测试
*/
}

@Russell Yes,已尝试但失败。您正在创建一个NSDictionary,它不能存储本质类型的数组,只能存储NSArray,NSArray只能存储对象类型,因此,在将UInt8存储到数组中之前,您需要存储一个NSNumber数组,并将UInt8装箱到NSNumber中,或者使用一个本机Swift字典,该字典可以存储UInt8Int/UInt数组(和Float/Double)自动桥接到NSNumber,但像UInt8这样的固定大小整数类型则不能。@Paulw我用本机Swift字典尝试过这一点,但还是失败了。var dict=Dictionary()dict[“type”]=type dict[“content”]=content@Martin但是我需要一个UInt8数组,那么如何处理呢?我是一个ios新手。当然你所做的是对的,但是你的字典只能把UInt8数组作为值,不能把其他类型(String,Int等)放进去。我需要一个字典,可以把字符串值,int值和UInt8数组值。这取决于你,你想在你的字典存储什么。。。查看我的更新我想要这样的内容:var type:String=“test”var content:[UInt8]=[1,2,3,4]var dict:Dictionary=[:]dict[“type”]=type dict[“content”]=content您所做的是数组中的任何类型,我想要字典值的多种类型因此,是否要在字典中存储任何值?请参见我的“最终”示例:-)
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
    */
}