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 に答える