Several types of variables in Swift
The variables in swift are divided into optional,non-optional and implicitly unwrapped optional these types
var nullableProperty : AnyObject? // optional
var nonNullProperty : AnyObject // non-optional
var unannotatedProperty : AnyObject! // implicitly unwrapped optional
Among them,optional (such as anyobject? ) values can contain nil values, and ( anyobject! ) is not a nil value, it will crash when forced to expand without a value; Anyobject) must be assigned in advance to be able to use it, and no value will crash after forced expansion
The following are the correspondence between several variables and OC variables
Attached source
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var nullableProperty : AnyObject? // optional
var nonNullProperty : AnyObject // non-optional
var unannotatedProperty : AnyObject! // implicitly unwrapped optional
nullableProperty = UIColor.redColor()
nonNullProperty = UIColor.redColor()
unannotatedProperty = UIColor.redColor()
print(nullableProperty)
print(nonNullProperty)
print(unannotatedProperty)
}
}
Several types of variables in Swift