I'm using the power source notification API on OS X and it is handing
me dictionaries containing CFNumberRef objects. How can I safely read
those inside swift and turn them into integers (or whatever they're
supposed to be)?
> I don't suppose you could provide a code sample? I'm afraid I'm too
> much of a beginner to understand exactly what this implies.
Sure. (I would’ve done that in the first place if I’d had my Mac handy.) Just paste the following into a new playground:
//: Number Bridging Playground
//: So, let's make a `CFNumber` to work with.
let myCFNumber: CFNumber = 3.14159
//: `CFNumber` and `NSNumber` are toll-free bridged—at the Objective-C level, they are completely
//: interchangeable to the point that you can just cast the bits of one to the other.
//: This also means that in Swift, you can cast a `CFNumber` directly to an `NSNumber`.
//: This is an "upcast"—it can't fail—so you can just use `as`, not `as?` or `as!`.
let myNSNumber = myCFNumber as NSNumber
//: Now that it's an `NSNumber`, you can use `NSNumber`'s methods and properties.
//: Or you can cast to a numeric type, which Swift allows as part of its Objective-C bridging.
//: (This is not quite the same as toll-free bridging—`NSNumber` and `Int` aren’t really interchangeable,
//: but as a convenience, Swift converts automatically when you cast between them.)
//: Again, these are upcasts so you can just use `as`.
myNSNumber as Int
myNSNumber as Double
//: In fact, you can even do that to the `CFNumber` directly, without first casting to `NSNumber`.
myCFNumber as Int
myCFNumber as Double
//: So, in conclusion, `CFNumber` and `NSNumber` are exactly equivalent to one another. Either one
//: can be cast to a Swift numeric type like `Int` or `Double` and Swift will convert them for you.
//: Hope this helps!