LoginSignup
10
9

More than 5 years have passed since last update.

switch文でオプショナル型をキャストしつつunwrap

Last updated at Posted at 2015-11-18

swift2.1で試してみたらできた。

let array: [Any?] = [1, "hoge", nil, UIViewController()]

for value in array {
    switch value {
    case let int as Int: print("Int: \(int)")
    case let string as String: print("String: \(string)")
    case nil: print("nil")
    case let vc as UIViewController: print("UIViewController: \(vc)")
    default: break;
    }
}

case let [unwrap後の変数名] as [型名]

switch文の中にcase nilも書けるためか、if letの時と違ってas?ではないみたい。

結果

Int: 1
String: hoge
nil
UIViewController: <UIViewController: 0x7fa190c2be10>
10
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
10
9