Search code examples
iosarraysswiftuint

Swift dictionary put [UInt8] as a value does not work


I create a dictionary in Swift:

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

I get an error: Cannot convert value of type [UInt8] to expected argument type 'AnyObject?', but if I change the content type as [UInt], it will work fine. Why?

In fact, I want to define a byte array as in Java, so I want to use [UInt8], anyone could help me?


Solution

  • you can use Swift native types

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

    i recommend you to use native Swift type as much as you can ... Please, see Martins's notes to you question, it is very useful!

    if the case is you want to store there any value, just define you dictionary as the proper type

    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]]
    

    to see, that the type of the value is still well known, you can check it

    dict["second"]?.forEach({ (element) -> () in
        print(element, element.dynamicType)
    })
    
    /*
    alfa String
    1 Int
    1 UInt
    C C
    */
    

    if you want to store Any value, you are free to do it ...

    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
        */
    }