2
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] if文 を if式 にしてみた

Posted at

##if文は式じゃないから値をかえさないですよね。
条件によってある変数に異なる異なる値を与える、なんてことは日常的にありますが、swiftではifは関数ではありませんので値を返すことをしません。変数への代入は各ブロックの中で行うことになります。

let val: Int

if conditionA {
   val = val1
} else if conditionB {
   val = val2
} else if let val3 = doSome() {
   val = val3
} else {
   val = val4
}

では、このif文を関数化してみましょう!

##やってみた

class ConditionalBranch<T> {
    private var val: T?

    func `if`( _ bool: Bool, _ ex: () -> T ) -> ConditionalBranch<T> {

        if bool {
            val = ex()
        }
        return self
    }

    func ifLet<E>(_ some: E?, ex: (E) -> T ) -> ConditionalBranch<T> {

        if val != nil {
            return self
        }

        guard let wapped = some else {
            return self
        }

        val = ex(wapped)
        return self
    }

    func elseIf( _ bool: Bool, _ ex: () -> T ) -> ConditionalBranch<T> {
        if val != nil { return self }
        return self.if(bool,ex)
    }

    func `else`(_ ex: () -> T) -> T {
        return val ?? ex()
    }
}

使い方はこんな感じです。

let val =
       ConditionalBranch<Int>()
       .if(conditionA) {
           return val1
        }
        .elseIf(conditionB) {
            return val2
        }
        .ifLet(doSome()) { val3 in
            return val3
        }
        .else {
            return val4
        }

想像以上に綺麗!(自己満足)なので、Swift6で採用してもらいたいです 笑

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