LoginSignup
8
1

More than 5 years have passed since last update.

[Swift] お前、rethrowsだったのかよ...

Last updated at Posted at 2018-11-18

こういう関数があったとしましょう。

func hoge() throws -> Bool {

   // それほど時間のかからない処理
   return result
}

func fuga() throws -> Bool {

  // 結構時間のかかる処理
  return result
}

この2つの関数のうちのいずれかが true なら特定の処理をするとします。

普通に書くとこうなります。


do {
  if try hoge() || try fuga() {
    // 処理
  }
}
catch {}

swiftcさん

error: 'try' cannot appear to the right of a non-assignment operator

だめだー!

書き直します。


do {
  if try hoge() {
    //処理
  } else if try fuga() {
    // 上と同じ処理
  }
}
catch {}

ありえねぇ!!!

書き直します。


do {
  let isHoge = try hoge()
  let isFuga = try fuga()
  if isHoge || isFuga {
    // 処理
  }
}
catch {}

不要かもしれないのに必ず時間のかかるfuga()を実行してるのつらい。

実はこのように書けます。
@t_ae さんにコメントをいただきさらに簡略化しました)


do {
  if try hoge() || fuga() {
    // 処理
  }
}
catch {}

|| さん、 お前、rethrowsだったのかよ...

8
1
2

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
8
1