When writing a new swift class, I'm still not 100% comfortable when (not) to use implicitly unwrapped optionals as opposed to just plain optionals. As far as I can tell, it should be ok to assign something as implicitly unwrapped (and optional) if you never expect it's value to be nil. If it is nil, it's an exceptional event and should cause a runtime error.
Take, for example, this simple sign-in view that contains two textfield member variables:
class SignInFieldView : UIView {
var emailField: UITextField!;
var passField: UITextField!;
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
commonInit();
}
convenience override init(frame: CGRect) {
self.init(frame: frame);
commonInit();
}
func commonInit() {
layoutEmail();
layoutPass();
}
// MARK: Layout Text Fields
func layoutEmail() {
let rect = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.size.width, height: (bounds.size.height * 0.5));
emailField = UITextField(frame: rect);
addSubview(emailField);
}
func layoutPass() {
let rect = CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height * 0.5), width: bounds.size.width, height: (bounds.size.height * 0.5));
passField = UITextField(frame: rect);
addSubview(passField);
}
}
In the above class, both emailField and passField are classified as implicitly unwrapped optionals because I never expect them to be nil throughout the life of their superview. I don't assign them as constants because I want their initialization to be dependent on the state of the superview (frame / bounds / etc). I left out that extra code to keep this example clean.
Is using implicitly unwrapped optionals for members of initialization a proper and valid use?