LoginSignup
6
7

More than 5 years have passed since last update.

【Swift】if式を実装

Last updated at Posted at 2016-10-05

Haskell等の関数型言語のif式に憧れ、Swiftで実装してみました。

// 値を返すif文
func `if`<A>(_ condition: () -> Bool, then: () -> A, else: () -> A) -> A {
    if condition() {
       return then()
    } else {
        return `else`()
    }
}

使用例

let result = `if`({ true },
                  then: { 1 },
                  else: { 2 })
// result = 1

ジェネリクスのおかげで以下はエラーになります。

let result2 = `if`({ false },
                   then: { 0 },
                   else: { "1" }) // 戻り値の型が一致しない

追記08/10/16

三項演算子を使ってスッキリさせました。
また @rizumita さんのコメントを受け@autoclosureを使ってみました。

func `if`<A>(_ condition: () -> Bool,
          then: @autoclosure () -> A,
          else: @autoclosure () -> A) -> A {
    return condition() ? then() : `else`()
}
6
7
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
6
7