Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created June 13, 2015 14:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davbeck/d4686dac04647c60ac56 to your computer and use it in GitHub Desktop.
Save davbeck/d4686dac04647c60ac56 to your computer and use it in GitHub Desktop.

It's kind of funny that Swift loses the object wrapper notation from ObjC (NSNumber *number = @(aPrimitive)). While NSNumber conforms to FloatLiteralConvertible, IntegerLiteralConvertible, and BooleanLiteralConvertible, if you have an existing value in a primitive format, you have to use the full initializer name for that given type. It feels very weird in Swift, which is all about type inference, that it can't infer what type of NSNumber to use. Even worse, because C and Swift use different names for their types, it can be confusing knowing which initializer to user.

In Swift 2, we can mark methods as being Swift only, which allows us to create our own initializers using Swift's infered initializer syntax. Previously the compiler would complain that the methods were identical to their existing ObjC counterparts.

extension NSNumber {
@nonobjc convenience init(_ value: Bool) {
self.init(bool: value)
}
@nonobjc convenience init(_ value: Float) {
self.init(float: value)
}
@nonobjc convenience init(_ value: Double) {
self.init(double: value)
}
@nonobjc convenience init(_ value: Int8) {
self.init(char: value)
}
@nonobjc convenience init(_ value: Int16) {
self.init(short: value)
}
@nonobjc convenience init(_ value: Int32) {
self.init(int: value)
}
@nonobjc convenience init(_ value: Int64) {
self.init(longLong: value)
}
@nonobjc convenience init(_ value: Int) {
self.init(integer: value)
}
@nonobjc convenience init(_ value: UInt8) {
self.init(unsignedChar: value)
}
@nonobjc convenience init(_ value: UInt16) {
self.init(unsignedShort: value)
}
@nonobjc convenience init(_ value: UInt32) {
self.init(unsignedInt: value)
}
@nonobjc convenience init(_ value: UInt64) {
self.init(unsignedLongLong: value)
}
@nonobjc convenience init(_ value: UInt) {
self.init(unsignedInteger: Int(value))
}
}
let theInt: Int = 45
NSNumber(theInt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment