4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftの条件分岐

Last updated at Posted at 2015-06-16

if文

let tokuten = 85
if tokuten >= 80 {
  println("素晴らしい")
}
println("\(tokuten)点でした")

else

  • arc4random_uniform(20)でランダム
let tokuten = arc4random_uniform(20) + 50
if tokuten >= 60 {
  println("合格です")
} else {
  println("不合格です")
}
println("\(tokuten)でした")

else if

let tokuten = arc4random_uniform(100) + 1
if tokuten < 30 {
  println("頑張れ")
} else if tokuten < 80 {
  println("合格")
} else {
  println("素晴らしい")
}
println("\(tokuten)点")

switch文

let theColor = "green"
switch theColer {
case "red", "yellow" :
  println("注意")
case "green" :
  println("快適")
case "gray" :
  println("停止中")
default:
  println("順調")
}

switch(レンジ)

for _ in 1...20 {
  let num = arc4random_uniform(50)
  print("\(num)")
  switch num {
  case (10...15):
    print(":交換:")
  case 20, (31...35), 40 :
    print(":再検査:")
  default :
    print(":合格:")
  }
}

switch(タプル)

let size = (15, 9)
switch size {
case (0, 0):
  println("どちらも0")
case (5...10, 5...10):
  println("規定")
case (_ , 5...10):
  println("幅\(size.0)おかしい")
case (5...10, _):
  println("高さ\(size.1)おかしい")
default:
  println("どっちもおかしい")
}

バリューバインディング

let size = (h: 9, w: 2)
switch size {
case (0,0):
  println("どっちも0")
case (5...10, 5...10):
  println("規定さいず")
case (5...10, let width):
  println("幅\(width)おかしい")
case (let height, 5...10):
  println("高さ\(height)おかしい")
default:
  println("どちらもおかしい")
}

バリューバインディング(where)

let size = (45, 40, 100)
switch size {
case let (width, height, _) where (width >= 50) || (height >= 50):
  println("高さ\(height)か幅\(width)がおかしい")
case let (_, _, weight) where (weight > 80):
  println("重さ\(weight)おかしい")
default:
  println("規定サイズ")
}

Swiftcase 文は break はいらない。
下に通したい場合は fallthrough

詳しくは
http://www.amazon.co.jp/%E8%A9%B3%E7%B4%B0%EF%BC%81Swift-iPhone%E3%82%A2%E3%83%97%E3%83%AA%E9%96%8B%E7%99%BA-%E5%85%A5%E9%96%80%E3%83%8E%E3%83%BC%E3%83%88-Swift-Xcode-ebook/dp/B00QT1VE2W/ref=sr_1_2/375-3245914-7632660?ie=UTF8&qid=1434472733&sr=8-2&keywords=swift

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?