Swift double unwrapping of Optionals Swift double unwrapping of Optionals xcode xcode

Swift double unwrapping of Optionals


The problem is that NSWorkspace().runningApplications returns anarray of AnyObject which has to be cast to an array of NSRunningApplication:

let apps = NSWorkspace().runningApplications as! [NSRunningApplication]let filteredApps = apps.filter {        $0.activationPolicy == NSApplicationActivationPolicy.Regular}for app in apps {    let name: String = app.localizedName!}


Here's why: app is of type AnyObject (id in Objective-C), and doing any lookup on AnyObject introduces a layer of optionality because of the possibility that the method doesn’t exist on the object. localizedName is itself Optional, so you end up with two levels of optional: the outer level is nil if the object doesn’t respond to localizedName, and the inner is nil if 'localizedName' is nil.