本文へスキップ
Hironobu Iga

Swift の switch と Kotlin の when を対比する

iOS 中心にやっていると Kotlin の when の書き方を毎回思い出すことになるので、両者を並べて比較したメモです。

公開日
更新日

この記事は別サイトにも掲載しています。 https://iganin.hatenablog.com/entry/2019/08/14/210620

はじめに

条件分岐を実装する際に if else 以外に Swift では switch、Kotlin では when を使用します。 基本的には iOS 開発を行っていますので、Kotlin の when 文を書く際に書き方を思い出すのに少し時間がかかることがあり、学習の意味もかねて両者の比較を行います。

環境設定

以下の環境を使用しています。どちらも Web 上の Playground です。

比較

Kotlin の条件分岐で使用される when では、when (対象の値) の後に 条件 -> 式 で分岐後の挙動を記載します。 デフォルトの条件(記載されている条件全てに当てはまらなかった場合)は else で記載します。 また、Kotlin では when 式 を変数に格納できることも特徴です。

enum class SampleValue {
    a,
    b,
    c,
    d
}

fun main() {
    var string = "sample"
    when (string) {
        "sample" -> {
            println("this is sample")
        }
        "hoge" -> {
            println("this is hoge")
        }
        "huga" -> {
            println("this is huga")
        }
        else -> {
            println("other")
        }
    }

    val constant = when (string) {
        "sample" -> "sample"
        else -> "others"
    }

    val sampleValue = SampleValue.a

    when (sampleValue) {
        SampleValue.a, SampleValue.b -> println("a or b")
        SampleValue.c -> println("c")
        SampleValue.d -> println("d")
    }
}

Swift の switch では switch 対象の値 の後に case 条件: 式 の形で分岐後の挙動を記載します。 デフォルトの条件(記載されている条件全てに当てはまらなかった場合)は default: 式 で記載します。 また、Swift では switch をそのまま変数に代入することはできません。似たことを行いたい場合はクロージャの返却値として代入する必要があります。

import Foundation

let sample = "sample"
let a: String = {
    switch sample {
        case "sample": return "sample"
        default: return "other"
    }
}()

switch sample {
case "sample": print("this is sample")
case "hoge": print("this is hoge")
case "huga": print("this is huga")
default: print("this is other")
}

enum Value: Int {
    case a = 0
    case b
    case c
    case d
}

let valueSample: Value = .a

switch valueSample {
    case .a, .b: print("a or b")
    case .c: print("c")
    case .d: print("d")
}

8/29 追記

Twitter にてアドバイスいただいたので追記します。 Kotlin の when では Smart Cast が効くようです。 具体的には下記のようなコードを書いたときに、is Int のように型の一致で式を実行する際、式に入ったときにはすでに x は Int 型に Cast されているため、型キャストの必要がなく Int 型として扱うことができます。

when (x) {
  is Int -> Do Something ( この段階で x は Int 型として認識されているので x + 1 = 2 となる)
  is String -> Do Something(この段階で String として認識されているため、たとえば x + 1 とすると 11 のように出力される)
  else -> Do Something
}

[毎日 Kotlin] Day9.Smart casts(スマートキャスト) | DevelopersIO