NSNumber(booleanLiteral: true) alternate syntax

Asked on 10/03/2024

1 search

In Swift, NSNumber(booleanLiteral: true) is a way to create an NSNumber object that represents a boolean value. However, in Swift, you can use a more straightforward syntax to represent boolean values directly using Swift's native Bool type. For example, you can simply use true or false as boolean literals.

If you are working with Swift and need to use NSNumber for compatibility with Objective-C APIs, you can create an NSNumber from a Bool like this:

let number = NSNumber(value: true)

This approach is more idiomatic in Swift when you need to bridge between Swift and Objective-C.

For more information on Swift's features and design, you might find the session A Swift Tour: Explore Swift’s features and design helpful, which covers various aspects of Swift, including value types and mutability.