LoginSignup
9
7

More than 5 years have passed since last update.

as と is の入った switch 文を if 文で記述してみる

Last updated at Posted at 2014-06-19

Swiftに関するメモ その7 - 型変換で触れたとおり、switch 文の case には asis が使えます。

Swift っぽい感じのプログラミングになって楽しいんですが、反面、慣れるまでは少し分かりづらいかもしれません。

The Swift Programming Language (iBooks Store) の「Type Casting」にある switch 文のサンプルを if で書き換えてみました。

共通部

class Movie {
  var director: String
  var name: String
  init(name: String, director: String) {
    self.director = director
    self.name = name
  }
}

var things = Any[]()

things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append(-3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(nil)
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))

という部分は共通で、The Swift Programming Language のサンプルコードは……

switch サンプルコード

for thing in things {
  switch thing {
  case 0 as Int:
    println("zero as an Int")
  case 0 as Double:
    println("zero as a Double")
  case let someInt as Int:
    println("an integer value of \(someInt)")
  case let someDouble as Double where someDouble > 0:
    println("a positive double value of \(someDouble)")
  case is Double:
    println("some other double value that I don't want to print")
  case let someString as String:
    println("a string value of \"\(someString)\"")
  case let (x, y) as (Double, Double):
    println("an (x, y) point at \(x), \(y)")
  case let movie as Movie:
    println("a movie called '\(movie.name)', dir. \(movie.director)")
  default:
    println("something else")
  }
}

それを if に書き換えると……

if サンプルコード

for thing in things {
  if thing as? Int == 0 {
    println("zero as an Int")
  } else if thing as? Double == 0 {
    println("zero as a Double")
  } else if let someInt = thing as? Int {
    println("an integer value of \(someInt)")
  } else if thing as? Double > 0 {
    let someDouble = thing as Double
    println("a positive double value of \(someDouble)")
  } else if thing is Double {
    println("some other double value that I don't want to print")
  } else if let someString = thing as? String {
    println("a string value of \"\(someString)\"")
  } else if let (x, y) = thing as? (Double, Double) {
    println("an (x, y) point at \(x), \(y)")
  } else if let movie = thing as? Movie {
    println("a movie called '\(movie.name)', dir. \(movie.director)")
  } else {
    println("something else")
  }
}

アセンブリコードレベルで同じかどうかまでの確認はしていません。あしからず。

9
7
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
9
7