Search code examples
swiftnsnumber

Why can a numeric literal be interpreted as an NSNumber in Swift?


Why is the following piece of code possible in Swift?

import Foundation
let n: NSNumber = 35.5

NSNumber is a type defined in the Foundation module and is not defined as a native type in Swift. How can the literal of 35.5 be interpreted as a value of NSNumber?


Solution

  • NSNumber conforms to the ExpressibleByBooleanLiteral, ExpressibleByFloatLiteral and ExpressibleByIntegerLiteral protocols, which means that it can be initialized from a boolean, floating point, or integer literal:

    let n1: NSNumber = false
    let n2: NSNumber = 12.34
    let n3: NSNumber = 123