-2

What is the equivalent in Swift of objc's:

NSObject* x = nil;
if(x) {
    //do stuff
}

Also what is the equivalent of:

if(!x) return;

In swift you must use {} for some reason?

  • Have a look at [When should I compare an optional value to nil?](http://stackoverflow.com/questions/29717210/when-should-i-compare-an-optional-value-to-nil). – Martin R Aug 09 '16 at 07:53
  • *"In swift you must use {} for some reason?"* – That is covered in the chapter "A Swift Tour" very early in the Swift book. – Martin R Aug 09 '16 at 08:00
  • Sorry Martin, I'm asking whether or not there is a shorthand way to say if(nil == nil) return; Most other languages allow one liners. – Maitland Marshall Aug 09 '16 at 08:35
  • 1
    Swift allows one-liners as well but it requires also the braces after an `if` statement. Just add `!= nil` and the braces and you're done. PS: And remove the trailing semicolon. – vadian Aug 09 '16 at 08:41

1 Answers1

0

Yes, in swift you should always use curly braces with if operator:

var x: NSObject? // value of Optional type set to nil automatically
if let x = x {
    //do stuff
}

here you used optional binding, you declared local variable x inside if scope. In start of function also guard keyword is useful:

guard let x = x else {return}
//do stuff

If you for some reason wish to use unwrapped original variable (thought you always have access to properties with self keyword, self.x - property, x - local scope variable), you should just compare it to nil:

if x != nil {
    //do stuff
}

or

if x == nil {return}
Yury
  • 6,044
  • 3
  • 19
  • 41