5
4

More than 1 year has passed since last update.

[Swift 5.9] if and switch expressions

Posted at

概要

Swift 5.9で導入されたif switch式について。

SE-0380 • if and switch expressions

This proposal introduces the ability to use if and switch statements as expressions, for the purpose of:

・Returning values from functions, properties, and closures;
・Assigning values to variables; and
・Declaring variables.

特に、Assigning values to variables; and について取り上げてみます。

Assigning values to variables

例えば、switchで判定した結果を変数の値に代入したいケース。Swift 5.8以前だと、こういう書き方がありそうです。

sushi.swift
enum Sushi {
    case squid
    case octopus
    case salmon
}

func canEat(_ sushi: Sushi, with money: Int) -> Bool {
    let price = { // enum内でcomputed propertyとして持てばいいんですが、例として。
        switch sushi {
        case .squid:
            return 100
        case .octopus:
            return 150
        case .salmon:
            return 200
        }
    }()

    return money >= price
}

それか後は、let price: Intで宣言してからswitch文の中で代入するやり方とか?

kotlinのwhenだともう少し簡潔にできるはず。そのため、個人的には若干もどかしさを感じる部分でした。

Xcode 15 betaのplaygroundsで試してみます。↓

sushi_on_xcode15beta.swift
func canEat(_ sushi: Sushi, with money: Int) -> Bool {
    let price = switch sushi {
        case .squid: 100 // return省略できる
        case .octopus: 150
        case .salmon: 200
    }

    return money >= price
}

assert(!canEat(.salmon, with: 150))
assert(canEat(.salmon, with: 200))

シンプルになりました。アサーションコードも通る。

感想

個人的には使いそう、という感じ。世間的にはどうなんでしょう。そんなに有用かな?という意見も少し見ました。

if switchの各節でreturn省略できるのは、関数内が単一式なら省略できるアレの応用的な感じでしょうか。


Variadic Genericsも気になります

5
4
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
5
4