Home » Swift » Swift Boolean Literals (Obj-C @YES @NO equivalent)

Swift Boolean Literals (Obj-C @YES @NO equivalent)

Posted by: admin November 30, 2017 Leave a comment

Questions:

In Objective-C, you can type @YES instead of [NSNumber numberWithBOOL:YES]. This makes for much tidier code.

In Swift, I’m having to write NSNumber.numberWithBool(true), which is kind of ugly.

Is there an equivalent to @YES and @NO in Swift?

Thanks in advance for your help!

Answers:

it is true and false

xcrun swift
Welcome to Swift!  Type :help for assistance.
  1> import Foundation
  2> var t : NSNumber = true
t: __NSCFBoolean = {}
  3> var f : NSObject = false
f: __NSCFBoolean = {}
  4>

read this: https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html#//apple_ref/doc/uid/TP40014216-CH6-XID_43

Swift automatically bridges certain native number types, such as Int and Float, to NSNumber. This bridging lets you create an NSNumber from one of these types

All of the following types are automatically bridged to NSNumber:

  • Int
  • UInt
  • Float
  • Double
  • Bool
Questions:
Answers:

Swift automatically bridges certain native number types, such as Int
and Float, to NSNumber

“Using Swift with Cocoa and Objective-C” (iBook).

let foo : NSNumber = true
let bar = NSNumber(value: false)

Questions:
Answers:

I you don’t have Yes Or no in Swift, Bool true false you have.

If you use Objc-C and call function return Yes or No you may cast this

example
// isReady return Yes Or no of Objc-C

if let isReady = object?.isReady {
 //is ready = true or false of your object
}

Leave a Reply

Your email address will not be published. Required fields are marked *