iOS / Swift Error throw, throws, try, catch
2019-05-02
summary
- Error를 throw하고 throws catch 하는 방법 간단히 정리
- Swift5, Xcode10
addnew function
func addNew(username: String, password: String) throws -> Bool {
// do something...
guard status == errSecSuccess else {
throw KeychainError.unhandledError(status: status)
}
return true
}
viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
let ret = try? addNew(username: username, password: password)
if ret == false {
print("failed")
} else {
print("success!")
}
}
// or
override func viewDidLoad() {
super.viewDidLoad()
do {
let _ = try addNew(username: username, password: password)
} catch {
print(error.localizedDescription)
}
}
Error enum
enum KeychainError: Error {
case noPassword
case unexpectedPasswordData
case unhandledError(status: OSStatus)
}