[Swift_tip 1] Conditional Statements, foreach, enum, for, unwrapping
Conditional Statements
import UIKit
var isTurnOn : Bool = true
// 1
if (isTurnOn == true) {
print("It's on")
} else {
print("It's off")
}
// 2
if isTurnOn == true {
print("It's on")
} else {
print("It's off")
}
// 3
if isTurnOn {
print("It's on")
} else {
print("It's off")
}
// 4
var msg : String = isTurnOn == true ? "It's on" : "It's off"
print("\(msg)")
// 5
var msg2 : String = isTurnOn ? "It's on" : "It's off"
print("\(msg2)")
For in
import UIKit
// Collection - Arrays, Sets, Dictionaries
// Array
var myArray : [Int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for item in myArray {
print("item: \(item)")
}
for item in myArray where item > 5 {
print("Bigger than 5: \(item)")
}
for item in myArray where item % 2 == 0 {
print("even: \(item)")
}
for item in myArray where item % 2 != 0 {
print("odd: \(item)")
}
enum
enum Animal {
case tiger
case lion
case wolf
case tiger, lion, wolf
}
let yourAnimal = Animal.tiger
print("yourAnimal: \(yourAnimal)")
print("yourAnimal: ", yourAnimal)
enum Attack : Int {
case damageTen = 10
case damageFive = 5
}
let yourAttack = Attack.damageTen
print("yourAttack: \(yourAttack)")
enum AnimalDetail {
case tiger(name: String)
case lion(name: String)
case wolf(name: String)
func getName() -> String {
switch self {
case .tiger(let name):
return name
case let .lion(name):
return name
case .wolf(let name):
return name
}
}
}
let yourTigerName = AnimalDetail.tiger(name: "Sangun")
print("yourTigerName: \(yourTigerName.getName())")