view raw
rb612 rb612 - 11 months ago 36
Swift Question

Returning an Unwrapped Optional in Swift?

When I was sifting through some of the class discussions for AVFoundation, I stumbled upon the following:

class func defaultDeviceWithMediaType(mediaType: String!) -> AVCaptureDevice!

Because optionals are a new concept to me, I'm a bit confused.

The discussion says that this method could either return "the default device with the given media type, or nil if no device with that media type exists." However, if there is a possibility that it's returning nil, why do they unwrap this optional in the return statement? Shouldn't it be

Then, when looking at an example that utilizes the above method, I find the following:

public lazy var device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

public func hasFlash() -> Bool {
if let d = self.device {
return d.hasFlash
return false

From what I understand, you would use an
if let
statement when you have an optional, but because the class
returns an unwrapped variable, why is having an
if let

Thank you so much in advance.


Implicitly unwrapped optional is basically an optional, that gets an ! everywhere you use it. Thats it.

var number: Int? = ...

//is the same as this:
var number: Int! = ...

An implicitly unwrapped optional is only to save you the need of unwrapping it every time you use it, wether with if let or with an !, but it has the same optionality of being nil as a normal optional.

A popular use of Implicitly unwrapped optionals is with outlets - they can't be non-optionals because we don't init them in the init of the VC, but we definitely have them later, so having them unwrapped saves us the need to do annoying things like if let table = self.tableView....