2.9 · Bridging to Objective-C Foundation types
Swift’s String, Array and Data were built to convert to and from the Objective-C classes underneath Foundation. That bridge is mostly invisible, and the places where it leaks are where the interesting bugs live.
Mental model. Bridging changes what kind of thing you hold, not just its name: a value type becomes an object with identity, and a typed number becomes an untyped NSNumber.
Bridging basics
What converts to what, what it loses, and what it costs.
- What is toll-free bridging, and how do you convert between Swift and Foundation types?
Many Swift value types map to a Foundation class: String to NSString, Array to NSArray, Dictionary to NSDictionary, Set to NSSet, Data to NSData, Date to… - Why does NSNumber confuse Bool, Int and Double, and how do you read untyped values safely?
An NSNumber stores a number but forgets its Swift type. NSNumber(value: 1) is simultaneously an Int, a Double and a Bool as far as casts go. Cast it to Bool… - What does bridging cost, and where does it show up in a profile?
Many conversions are O(1) wrappers, but not all. A Swift String that came from an NSString may keep the Objective-C storage and use slower UTF-16 paths. An…
Value types and objects
Which Foundation types copy, which share, and how equality works for NSObject.
- Which Foundation types are value types in Swift, which are classes, and what happens to mutable ObjC types?
Foundation’s Swift overlays turned types that behave like values into structs: Data, Date, URL, UUID, IndexPath, CharacterSet, Decimal, Measurement… - How does equality work for NSObject subclasses, and why do two “equal” objects stay distinct in a Set?
NSObject conforms to Equatable and Hashable through the Objective-C methods isEqual(_:) and hash. By default both use identity: two different instances are…
More in Foundation & stdlib
- 2.1 · Collections, indexing, Sequence and lazy
- 2.2 · Date, Calendar, Locale, TimeZone, FormatStyle
- 2.3 · URL, URLComponents, Data, FileManager
- 2.4 · NotificationCenter, KVO and Operation
- 2.5 · JSON coder options, property lists, UserDefaults
- 2.6 · Bundle, resources, localization tables
- 2.7 · NSCache and locks
- 2.8 · Attributed strings, scanners, number formatters