Monday, April 13, 2015

Swift optional variable ? ! as?

var v : UIView?
   the variable v may be nil or may be a valid UIView Object

var uv = v!
   although v is optional, but when the above line is executed, developer promises the v points to a valid uiView object, otherwise, the app will crash

var m = v?.backgroundColor
   if v is nil, the express return nil. Otherwise, returning the UIView's background color

if let t = v {
   var h = t.backgroundColor
}
else{
}
  combine if check with optional variable. t is not optional

var k : UIView!
var bc =  k.backgroundColor
  k, as an implicitly unwrapped optional type, is similar to option type, so we do no need to set an initial value when declaring and defining the variable, also we do no need to explicitly unwrap the variable with ! when assigning it to a non optional variable. 
However, when defining implicitly unwrapped option type, developer promised that whenever the variable is used, it will always have a valid value assign to it. so the variable will be set before its value is used. This type is mostly used for IBOutlet.

let a : UIView?= v as? UIView
 case v to UIView and assign to a. The result may be nil or an option variable points to a valid object

let m: UIView = v as UIView
  Developer guarantees the v points to a valid object

option chain
When accessing an optional variable's property or method, the variable must be unwrapped with either ? or !, so that if the variable is nil, the express can return nil gracefully. If the variable definitely has a value, then ! can also be used to unwrapped the variable.
var mainStoryBoard = window?.rootViewController?.storyboard


1 comment: