I was told that I could use try with a swift error, but when is it said? Isn't it just a guard? I was wondering, but it was a simple matter, so I will record it as a memorandum.
If "throws" is described in the definition method, you have to write the process to receive the error by try.
struct KeychainManager {
private static let keychain = Keychain(service: "com.example.github-token")
private static let tokenKey: String = "token"
static func getToken() -> String {
//The following will result in an error
guard let token = keychain.get(tokenKey) else { return "" }
return token
}
Error statement
Call can throw, but it is not marked with 'try' and the error is not handled
KeychainAccess
public func get(_ key: String, ignoringAttributeSynchronizable: Bool = true) throws -> String?
When I try to define and jump to the get method of KeychainAccess, the notation throws is displayed. In other words, you have to write a countermeasure to receive the thrown error.
When I used the do-catch syntax, the error disappeared. (You can just try? Without using do-catch, but you should handle the failure.)
static func getToken() -> String {
do {
guard let token = try keychain.get(tokenKey) else { return "" }
return token
} catch let error {
print(error)
return("")
}
}