Why is Swift Dictionary not bridgeable?

456 views Asked by At

Dictionary is a bridged type, why is it that I can switch from Swift dictionary to NSDictionary but not the other way around? (Compile Error: NSDictionary is not convertible to 'Dictionary')

According to Apple's doc:

All NSDictionary objects can be bridged to Swift dictionaries, so the Swift compiler replaces the NSDictionary class with [NSObject: AnyObject] when it imports Objective-C APIs.

import Foundation

var swiftDict = ["0": "zero"]

let nsDict:NSDictionary = swiftDict
let backToSwiftDict:Dictionary = nsDict
2

There are 2 answers

3
topher91 On

This is correct but you have to perform a type safe cast from NSDictionary to a Dictionary

var swiftDict = ["0": "zero"]

let nsDict: NSDictionary = swiftDict
let backToSwiftDict: Dictionary = nsDict as Dictionary
2
BadmintonCat On

... or you can cast it back into a dictionary with type-safe fields ...

var swiftDict = ["0": "zero"]
let nsDict:NSDictionary = swiftDict
let backToSwiftDict = nsDict as! [String:String]