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】コールバックを使ってAPIを叩いた結果毎に処理を分岐させる

Posted at

業務の中で使われていた手法を理解するために自分なりに単純化してみました。

擬似API処理

// APIを叩くメソッド
func api(closure: (ApiResult) -> Void) {
  // APIを叩く処理
  
  // APIから返ってきた結果
  closure(.SUCCESS)
}

// APIの通信結果
enum ApiResult {
  // 成功
  case SUCCESS
  // 失敗
  case ERROR
}

enumを使って発生しうる結果分岐を用意しておきます。作成した分岐経路を擬似的に作ったAPIを叩くメソッドのclosureに渡し、結果がどのcaseに当てはまるかを返してもらいます。

メソッドの呼び出し

メソッドを呼び出して、switchを使い結果毎にやってほしい処理を追加します。

api { result in
// resultにapi()の結果が入っている 
switch result {

// 成功だった時の処理
case .SUCCESS:
    print("SUCCESS")
    
// 失敗だった時の処理
case .ERROR:
    print("ERROR")
}

// 出力結果 "SUCCESS"

api().SUCCESSを返しており、resultの中には.SUCCESSが入っているので、
結果として"SUCCESS"が返されます。

参考記事
Swiftのクロージャによるコールバックの説明 - Qiita

間違っている点等あればご指摘いただけると幸いです。

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?