0

I noticed some methods, mainly in protocols has an ! in their params. As example this ones from UIImagePickerControllerDelegate:

protocol UIImagePickerControllerDelegate : NSObjectProtocol {
    @optional func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!)
    @optional func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!)
    @optional func imagePickerControllerDidCancel(picker: UIImagePickerController!)
}

What exactly means ! in this context?

tshepang
  • 12,111
  • 21
  • 91
  • 136
StuckOverFlow
  • 851
  • 6
  • 15
  • 2
    I don't think this should be closed. The referenced question answers the use of the exclamation mark on an Optional, to some novices it might not be obvious how implicitly unwrapped optionals relate to those because there is no `?` involved. – Pascal Jun 18 '14 at 14:24
  • I absolutely agree with Pascal. – Confused Jun 26 '14 at 20:09

1 Answers1

5

It is called an Implicitly Unwrapped Optional.

Sometimes it is clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be safely assumed to have a value all of the time.

Usually, when accessing an Objective-C API in Swift, you will see lots of these Implicitly Unwrapped Optionals because pointers in Objective-C can be nil. That means the variable must be optional, but to make the API feel more like Objective-C, we want to treat it like it is not optional.

Implicitly unwrapped optionals look and work like normal (non-optional) variables, but if they are indeed nil when you try to use them, you will get a runtime error and the whole program will be stopped. So use them sparingly yourself and be careful with them.

drewag
  • 93,393
  • 28
  • 139
  • 128