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?
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?
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}