Search code examples
swift3null-coalescing-operator

When in swift 3.0 nil coalescing used, didn't get expected result


Implemented below code where, if my dictionary doesn't have key "key1" then value1 should be initialized with blank dictionary [:], code executes but never comes into if-let block.

Suggest correct solution, in case i have used nil coalescing in a wrong way

if let value1 = ((dataDict["key1"] as? Dictionary<String,Any>?) ?? [:]){
print(value1) 
}

Solution

  • There is no need to use if - let in conjunction with the nil coalescing operator

    let value1 : Dictionary<String,Any> = dataDict["key1"] as? Dictionary<String,Any> ?? [:]
    print(value1) 
    

    or shorter

    let value1 = dataDict["key1"] as? [String:Any] ?? [String:Any]()