0

I know with exclamation mark I can unwrap an optional value, means I can convert optional type to a 'normal' type. But what about using exclamation in type identifier? I.e.

@IBOutlet weak var back: UIButton!

Why do I need !? Without ! it means back can not take a nil value, isn't it? As Int i means neither i can take a nil value. But then why I need ! in type identifier?

János
  • 32,867
  • 38
  • 193
  • 353
  • Check out this answer: http://stackoverflow.com/a/24583157/2592349 – Dániel Nagy Apr 08 '15 at 10:43
  • 2
    This question is a duplicate... but for the record, generally speaking **YOU** shouldn't use the `!`. Typically just use it when Xcode is generating code or autocompleting it in for you. – nhgrif Apr 08 '15 at 10:46
  • Consider the case of an object that may have nil properties while it's being constructed and configured, but is immutable and non-nil afterwards (NSImage is often treated this way, though in its case it's still useful to mutate sometimes). Implicitly unwrapped optionals would clean up its code a good deal, with relatively low loss of safety (as long as the one guarantee held, it would be safe). See: http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals – Michael Apr 08 '15 at 10:48

1 Answers1

1

@IBOutlet types need to be optional, otherwise the compiler would complain that the variables aren’t set in all initializers. Swift doesn’t “know” that Interface Builder is supplying the views at run time; therefore it would do its job and raise a build error about the unsupplied values.

Javier Flores Font
  • 2,075
  • 15
  • 13
  • Can I mark variables like this that are initialised in viewDidLoad, but not in init method? – János Apr 08 '15 at 10:53
  • yes but the use of implicit unwrapped optional (!) is very dangerous if improperly used, it will generate runtime exceptions if you try to use variables that haven't been initialized. Hope it helps. – Javier Flores Font Apr 08 '15 at 10:59