import Foundation surprises

When importing Foundation (or anything else like Cocoa or UIKit that will import it implicitly) Swift automatically converts some Objective-C types to Swift types, and some Swift types to Objective-C types, and a number of data types in Swift and Objective-C can be used interchangeably. Data types that are convertible or can be used interchangeably are referred to as bridged data types.


(You can read more about it here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html#//apple_ref/doc/uid/TP40014216-CH6-XID_43 )


This is nice of course, but it can also lead to the same code behaving in very different ways depending on if we import Foundation or not (ie if we are in a "Pure Swift Environment" or if the above mentioned bridging has been activated).


Here's one example:

import Foundation // Comment / uncomment this line.
let a = [1, 2, 3]
let b = [1, 2, 3]
print([a] == [b]) // Will print true or false depending on if Foundation is imported or not.


here's another:

import Foundation // Comment / uncomment this line.
let a = [[1, 2, 3], [4, 5, 6]]
let b = [[1, 2, 3], [4, 5, 6]]
print(a == b) // true or compile time error depending on if Foundation is imported or not.


and here's a third really peculiar one:

// import Foundation
let a: Int = 1234
print(a is AnyObject)
// Three different behaviours:
// 1. false --- If in Xcode project and no import Foundation
// 2. true  --- If in playground    and no import Foundation
// 3. Warning: "'is' test is always true" --- If Foundation is imported (Xcode project or playground)


Feel free to add more import-foundation-surprises to this thread.

import Foundation // Comment out to enable typechecking and compile time error! :P
print([1, 2, 3] == ["1", "2", "3"]) // false or compile time error depending on if Foundation is imported or not.

This line of code also helps you understand the section Numbers.

print([1, 2, 3 as Int] == [true, 2.0, 3 as UInt]) //->true with import Foundation

Type safe!

import Foundation surprises
 
 
Q