实际上错误可能来自NSAppleScript(source: script)!
因此正确的解决方案是返回一个可选字符串并且根本不使用强制展开:
func runAppleScript(script:String) -> String? {
let errorInfo: AutoreleasingUnsafeMutablePointer<NSDictionary?> = nil
let startAtLoginScript = NSAppleScript(source: script)
let theDescriptor = startAtLoginScript?.executeAndReturnError(errorInfo)
return theDescriptor?.stringValue
}
if let scriptResult = runAppleScript("tell app \"Spotify\" to playpause") {
NSLog("\(scriptResult)")
} else {
print("the script execution failed")
}
如果您希望在失败时使用默认值而不是 nil,则无需返回 Optional:
func runAppleScript(script:String) -> String {
let errorInfo: AutoreleasingUnsafeMutablePointer<NSDictionary?> = nil
let startAtLoginScript = NSAppleScript(source: script)
let theDescriptor = startAtLoginScript?.executeAndReturnError(errorInfo)
return theDescriptor?.stringValue ?? "" // if nil, returns the default ""
}
let scriptResult = runAppleScript("tell app \"Spotify\" to playpause")
NSLog("\(scriptResult)")
至于使用新的Swift 2错误处理系统,您在内部使用的所有方法都runAppleScript
不会抛出错误,因此只有在您使用自定义错误类型并自己抛出错误时才会起作用。例子:
enum MyAppleScriptError: ErrorType {
case ExecutingScriptFailed
case GettingStringValueFailed
}
func runAppleScript(script:String) throws -> String {
let errorInfo: AutoreleasingUnsafeMutablePointer<NSDictionary?> = nil
let startAtLoginScript = NSAppleScript(source: script)
guard let theDescriptor = startAtLoginScript?.executeAndReturnError(errorInfo) else {
throw MyAppleScriptError.ExecutingScriptFailed
}
guard let value = theDescriptor.stringValue else {
throw MyAppleScriptError.GettingStringValueFailed
}
return value
}
do {
let scriptResult = try runAppleScript("tell app \"Spotify\" to playpause")
NSLog("\(scriptResult)")
} catch {
print(error)
}
斯威夫特 3
相同的想法,但一些实现细节不同。
func runAppleScript(_ script:String) -> String? {
let errorInfo: AutoreleasingUnsafeMutablePointer<NSDictionary?>? = nil
if let startAtLoginScript = NSAppleScript(source: script) {
let theDescriptor = startAtLoginScript.executeAndReturnError(errorInfo)
return theDescriptor.stringValue
}
return nil
}
if let scriptResult = runAppleScript("tell app \"Spotify\" to playpause") {
NSLog("\(scriptResult)")
} else {
print("no return value")
}
并带有错误处理:
enum MyAppleScriptError: ErrorProtocol {
case ExecutingScriptFailed
case GettingStringValueFailed
}
func runAppleScript(_ script:String) throws -> String {
let errorInfo: AutoreleasingUnsafeMutablePointer<NSDictionary?>? = nil
let startAtLoginScript = NSAppleScript(source: script)
guard let theDescriptor = startAtLoginScript?.executeAndReturnError(errorInfo) else {
throw MyAppleScriptError.ExecutingScriptFailed
}
guard let value = theDescriptor.stringValue else {
throw MyAppleScriptError.GettingStringValueFailed
}
return value
}
do {
let scriptResult = try runAppleScript("tell app \"Spotify\" to playpause")
NSLog("\(scriptResult)")
} catch {
print(error)
}