use*_*368 5 error-handling swift
难道是当使用try?(可选尝试)调用没有返回值的throwing函数时,错误只是被忽略了吗?
func throwingVoidFunction() throws { . . . }
try? throwingVoidFunction()
Run Code Online (Sandbox Code Playgroud)
我希望编译器不允许try?在具有return type的throwing函数前面使用void,但是编译器不会抱怨。
那么try?在void函数之前使用该方法来吸收错误吗?(使用一个空的默认捕捉时,如:catch {})
编译器没有理由抱怨。返回类型为
func throwingVoidFunction() throws { ... }
Run Code Online (Sandbox Code Playgroud)
是Void,因此是表达式的类型
try? throwingVoidFunction()
Run Code Online (Sandbox Code Playgroud)
is Optional<Void>,如果在评估表达式时抛出错误,则其值为nil( == Optional<Void>.none) ,Optional<Void>.some()否则为。
您可以忽略返回值或针对nil. 忽略方法抛出的任何错误的优雅方式中给出了一个示例:
let fileURL = URL(fileURLWithPath: "/path/to/file")
let fm = FileManager.default
try? fm.removeItem(at: fileURL)
Run Code Online (Sandbox Code Playgroud)