The second method doesn't create a UIView, it simply declares a property that can hold a reference to a UIView. You have declared it as an implicitly unwrapped optional via !, which means that the compiler doesn't complain that you haven't initialised it, but you do still need to initialise it somewhere or you will get a runtime exception when you access it.
What you are really asking about is two slightly different ways to declare a property that can hold a reference to a UIView.
Swift requires that all properties are initialised with a value or declared as optional via ?. ! is a special case where an optional is implicitly unwrapped; The property is still an optional type, so it doesn't need to be initialised but you are telling Swift that you will initialise it and so it isn't necessarily for you to unwrap it when you use it.
For example, an @IBOutlet UIView property will be initialised when a view controller is loaded from a storyboard, so you can be confident that it will have a value (or something is misconfigured and you will get a crash), but that value isn't supplied by the initialiser, so the property needs to be an optional.
Declaring the property as an implicitly unwrapped optional makes the compiler happy even though it can't see where the property is initialised and saves you from having to conditionally unwrap the property each time you refer to it.
Your question is asking about programatically creating a UIView, so the method you use may depend on how you wanted to create the view.
If you just want a UIView and you are going to add constraints to it later, you can use:
var myView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
self.myView.backgroundColor = .green
self.myView.translatesAutoResizingMaskIntoConstraints = false
// Set up constraints
}
However, if you wanted to set up the view based on the frame of the superview, you might do something like this:
var myView: UIView!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.myView == nil {
self.myView = UIView(frame:self.view.frame)
self.myView.backgroundColor = .green
...
}
}
Generally it is best to avoid explicitly unwrapped optionals and force unwrapping unless you really are sure that it will have a value.
var myView3: UIView = { // Your implementation }(), varmyView4: UIView?.!this means value is exist and it's not optional.