Why print() is printing my String as an optional?

后端 未结 4 1918
醉酒成梦
醉酒成梦 2021-01-23 02:41

I have a dictionary and I want to use some of its values as a key for another dictionary:

let key: String = String(dictionary[\"anotherKey\"])

4条回答
  •  日久生厌
    2021-01-23 03:25

    A Swift dictionary always return an Optional.

    dictionary["anotherKey"] gives Optional(42), so String(dictionary["anotherKey"]) gives "Optional(42)" exactly as expected (because the Optional type conforms to StringLiteralConvertible, so you get a String representation of the Optional).

    You have to unwrap, with if let for example.

    if let key = dictionary["anotherKey"] {
        // use `key` here  
    }
    

    This is when the compiler already knows the type of the dictionary value.

    If not, for example if the type is AnyObject, you can use as? String:

    if let key = dictionary["anotherKey"] as? String {
        // use `key` here  
    }
    

    or as an Int if the AnyObject is actually an Int:

    if let key = dictionary["anotherKey"] as? Int {
        // use `key` here  
    }
    

    or use Int() to convert the string number into an integer:

    if let stringKey = dictionary["anotherKey"], intKey = Int(stringKey) {
        // use `intKey` here  
    }
    

提交回复
热议问题