Timbo
Timbo

Reputation: 1214

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

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!

Upvotes: 22

Views: 14670

Answers (3)

Daniel
Daniel

Reputation: 783

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)

Upvotes: 12

Bryan Chen
Bryan Chen

Reputation: 46608

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

Upvotes: 30

YanSte
YanSte

Reputation: 10839

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
}

Upvotes: 0

Related Questions