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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With