Branching
ในบางครั้งเราต้องการรันคำสั่งแตกต่างกันไปโดยขึ้นกับเงื่อนไขบางอย่าง ใน Swift จะมีวิธีการได้สองวิธี คือ ใช้ if
หรือ switch
If
สามารถเขียนได้เหมือนภาษาอื่นทั่วไป
if isCar && isNew {
print("new car")
} else if isCar {
print("old car")
} else {
print("not a car")
}
เราสามารถใช้ Ternary Conditional ได้แบบนี้ (เครื่องหมาย ? ต้องเว้น 1 เคาะ)
y = x > 4 ? 1 : 2
ส่วน switch
สามารถเขียนได้แบบนี้
let personAge = 7
switch personAge {
case 0..<1: print("baby")
case 1..<3: print("toddler")
case 3..<5: print("preschooler")
case 5..<13: print("gradeschooler")
case 13..<18: print("teen")
default: print("adult")
}
เราสามารถใส่เงื่อนไขในแต่ละเคสเพิ่มได้
let temperature = 21.5
let humidity = 22.0
switch (temperature, humidity) {
case let (t,h) where t > h: print("humidity lower")
case let (t,h) where t < h: print("humidity higher")
default: "humidity and temperature are the same"
}
สามารถใช้ tuple ได้ และสามารถนำค่าออกมาใช้ในเคสได้
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
switch
ยังใช้ในการถอดค่า associate value จาก Enum
enum PaymentType {
case cheque
case creditCard(number:String)
}
let payment = PaymentType.creditCard(number: "1234567890123456")
switch payment {
case .cheque: print("cheque")
case .creditCard(let number): print("credit card number: " + number)
}
Last updated