LoginSignup
18
9

More than 3 years have passed since last update.

Swiftの「case is」とか「case as」って何なの?

Last updated at Posted at 2019-04-29

Swiftでコードを書いているとたまに「case is」や「case as」といった書き方を目にします。
よくわからなかったので少し調べてみました。

case isとcase asの目的

case isやcase asはswitchに与えられた変数が特定の型にマッチしてるかどうか判定することを目的に使用されているみたいでした。
これだけではなんのことやらわからないと思うのでそれぞれ使用例を見てみましょう。

case isの使用例

case isはインスタンスの型チェックを行い、trueなら処理を行います。


case 変数 is  

例をあげるとこんな感じです。

var things: [Any] = []

things.append(0)
things.append("hoge")
things.append(2.5)

for thing in things {
    switch thing {
        case is String:
            print("string")
        case is Int:
            print("Int")
        case is NSObject:
            print("Object")
        default:
            break
        }
}

case asの使用例

case asは変数の型がキャスト可能かどうか判定し、可能であればキャストします。
キャストとは型を変換することです。

case as  

キャストした値を変数として定義し、case内の処理で利用することもできます。
僕はこっちの書き方が使いやすくて好きです。

case let 変数名 as 

例をあげるとこんな感じです。

for thing in things {
    switch thing {
    case let str as String:
        print("\(str)はStringにキャストされました") // hogeはStringにキャストされました
    case let int as Int:
        print("\(int)はIntにキャストされました") // 0はIntにキャストされました
    default:
        break
    }
}

まとめ

  • case isは変数の型を判定し、trueの場合処理を行う
  • case asは変数の型がキャスト可能かどうか判定し、可能であればキャストする。
18
9
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
18
9