Boon
Boon

Reputation: 41500

Why is Swift Dictionary not bridgeable?

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

Upvotes: 0

Views: 511

Answers (2)

BadmintonCat
BadmintonCat

Reputation: 9586

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

Upvotes: 1

topher91
topher91

Reputation: 222

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

Upvotes: 2

Related Questions