Swift double unwrapping of Optionals

user14492

I understand what optional are in Swift but I just encountered a ”Double Wrapped Optional’, where if I don’t use two '!' Xcode gives an complier error

Value of optional type 'String?' not unwrapped; did you mean to use '!' or ‘?'?

I have the following code, where app is of type NSRunningApplication.

let name: String = app.localizedName!

Why should I have to use two !? Isn’t one enough to unwrap the variable because it is of type var localizedName: String?.

Context: Xcode want me to use let name: String = app.localizedName!!, otherwise it gives the compiler error above. The app variable is defined as follow:

var apps = NSWorkspace().runningApplications.filter{$0.activationPolicy == NSApplicationActivationPolicy.Regular}
for app in apps{
    //code posted above
    …
}

So I know that app is not an optional and will always have a value, nor is it an optional application.

P.S. Is there a way to define type when using fast enumeration? Like for Foo(app) in apps where apps = [AnyObject].

Martin R

The problem is that NSWorkspace().runningApplications returns an array 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!
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related