LoginSignup
6
2

More than 1 year has passed since last update.

[Swift] Concurrency の関数で戻り値が Void 型の時に出るエラーを解消する

Last updated at Posted at 2022-07-11

はじめに

案外、情報がなかったのでメモ程度に載せておこうかと思います。

エラーに関して

Void 型に限らず、型が推測できないと同じエラーが出ます。

Generic parameter 'T' could not be inferred

具体例

以下のような関数があった場合に発生します。

.swift
func doSomething() async throws {
    try await withCheckedThrowingContinuation { [weak self] continuation in
        // 任意のAPIメソッドを呼び出したとする
        self?.apiClient.call() { result in
            switch result {
            case .success(let response):
                continuation.resume()
            case .failure(let error):
                continuation.resume(throwing: error)
            }
        }
    }
}

この場合の Void 型は、暗黙的に型が推論されないようです。

解決策

2パターンあるので載せておきます。

方法1

内部関数の引数(今回はCheckedContinuation)に型を明示的に指定してあげることで解決します。

func doSomething() async throws {
-   try await withCheckedThrowingContinuation { [weak self] continuation in
+   try await withCheckedThrowingContinuation { [weak self] (continuation: CheckedContinuation<Void, Error>) in
        self?.apiClient.call() { result in
            switch result {
            case .success(let response):
                continuation.resume()
            case .failure(let error):
                continuation.resume(throwing: error)
            }
        }
    }
}

方法2

末尾でキャストしてあげます。

func doSomething() async throws {
    try await withCheckedThrowingContinuation { [weak self] continuation in
        self?.apiClient.call() { result in
            switch result {
            case .success(let response):
                continuation.resume()
            case .failure(let error):
                continuation.resume(throwing: error)
            }
        }
-    }
+    } as Void // ← ここ
}

終わりに

どちらでも良いと思いますが、1つの目の型を明示する方が王道な気はします。
関数が横長になるのは嫌なので、個人的には2つ目の方が好みです。

参考文献

6
2
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
6
2