0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiftエラーでtry使えって言われるのはどんなとき?

Posted at

swiftエラーでtry使えって言われたけど どんなときに言われるの? guardだけじゃダメなの?
と疑問に思っていたが単純なことだったので備忘録として記録しておく。

最初に結論 

定義メソッドに「throws」が記述されていた場合は、tryでエラーを受け取る処理を書かなければいけない。

例文

struct KeychainManager {
    
    private static let keychain = Keychain(service: "com.example.github-token")
    private static let tokenKey: String = "token"

    static func getToken() -> String {
        // 下記だとエラーになる
        guard let token = keychain.get(tokenKey) else { return "" }
        return token
    }

エラー文

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?

KeychainAccessのgetメソッドに定義ジャンプしてみると throwsという表記が。
つまり投げられたエラーを受け取る対処を書かなかればいけない。

対応

do-catch構文にしたところ無事エラーが消えた。
(do-catchを使わなくてもtry?だけで済ますこともできるが、失敗をハンドリングしたほうがいいとのこと。)

static func getToken() -> String {
        do {
            guard let token = try keychain.get(tokenKey) else { return "" }
            return token
        } catch let error {
            print(error)
            return("")
        }
    }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?