はじめに
条件分岐を実装する際にif else以外に Swiftではswitch
、 Kotlinではwhen
を使用します。
基本的にはiOS開発を行っていますので、Kotlinのwhen文を書く際に書き方を思い出すのに少し時間がかかることがあり、
学習の意味もかねて両者の比較を行います。
環境設定
以下の環境を使用しています。どちらもWeb上のPlaygroundです。
- Swift - http://online.swiftplayground.run/
- Kotlin - https://play.kotlinlang.org
比較
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 }