Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't unwrap Optional.None with AutoreleasingUnsafePointer

Tags:

swift

Upon running NSAppleScript.executeAndReturnError with an Applescript command that should fail and return an error, I get a Can't unwrap Optional.None error for errorDict.

var errorDict: NSDictionary? = nil
var scriptObject:NSAppleScript = NSAppleScript(source: command)
var execute:NSAppleEventDescriptor = scriptObject.executeAndReturnError(&errorDict)

I understand that the error is due to unwrapping a nil optional variable, though executeAndReturnError must take an optional variable. How could I fix this?

like image 480
Andrew Deniszczyc Avatar asked Feb 24 '26 13:02

Andrew Deniszczyc


1 Answers

This error is most likely occurring while trying to initialize the NSAppleScript object, not your NSDictionary? object. NSAppleScript(source:) is a failable initializer, meaning it could return nil if an error occurs compiling your script. Your code should look something like this:

if let scriptObject = NSAppleScript(source: command) {
    var errorDict: NSDictionary? = nil
    let execute = scriptObject.executeAndReturnError(&errorDict)
    if errorDict != nil {
        // script execution failed, handle error
    }
} else {
   // script failed to compile, handle error
}

Sulthan's answer makes a good point, but as of Swift 1.2, executeAndReturnError(errorInfo:) no longer returns an Optional type even though it could return a nil (see this radar). The proper way to handle the execution failing is by checking the errorInfo dictionary for errors.

like image 60
mclaughj Avatar answered Feb 26 '26 09:02

mclaughj