Question
- Is it possible to replicate Swifts numeric value bridging to Foundation:s
NSNumber
reference type, for e.g.Int32
,UInt32
,Int64
andUInt64
types? Specifically, replicating the automatic by-assignment bridging covered below.
Intended example usage of such a solution:
let foo : Int64 = 42
let bar : NSNumber = foo
/* Currently, as expected, error:
cannot convert value of type 'Int64' to specified type 'NSNumber */
Background
Some of the native Swift number (value) types can be automatically bridged to NSNumber
(reference) type:
Instances of the Swift numeric structure types, such as
Int
,UInt
,Float
,Double
, andBool
, cannot be represented by theAnyObject
type, becauseAnyObject
only represents instances of a class type. However, when bridging toFoundation
is enabled, Swift numeric values can be assigned to constants and variables ofAnyObject
type as bridged instances of theNSNumber
class....
Swift automatically bridges certain native number types, such as
Int
andFloat
, toNSNumber
. This bridging lets you create anNSNumber
from one of these types:let n = 42 let m: NSNumber = n
It also allows you to pass a value of type
Int
, for example, to an argument expecting anNSNumber
. ...All of the following types are automatically bridged to NSNumber:
- Int - UInt - Float - Double - Bool
From Interoperability - Working with Cocoa Data Types - Numbers.
So why attempt to replicate this for the IntXX
/UIntXX
types?
Primarily: Curiosity, sparked by seeing some questions recently with underlying problems covering confusion over why an Int
value type seemingly can be represented by an AnyObject
(reference) variable, whereas e.g. Int64
, cannot; which is naturally explained by the bridging covered above. To pick a few:
- Why is a Swift Array<Int> compatible with AnyObject?
- Cannot subscript a value of type '[UInt32]'
- Using generic arrays in swift
None of Q&A:s above mentions, however, the possibility of actually implementing such automatic bridging to AnyObject
(NSNumber
) from the non-bridged types Int64
, UInt16
and so on. The answers in these threads rather focuses (correctly) on explaining why AnyObject
cannot hold value types, and how the IntXX
/UIntXX
types are not bridged for automatic conversion to the underlying Foundation types of the former.
Secondarily: For applications running at both 32-bit and 64-bit architectures, there are some narrow use cases—using Swift native number types implicitly converted to AnyObject
, in some context—where using e.g. Int32
or Int64
type would be preferred over Int
. One (somewhat) such example: