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")
}เราสามารถใส่เงื่อนไขในแต่ละเคสเพิ่มได้
สามารถใช้ tuple ได้ และสามารถนำค่าออกมาใช้ในเคสได้
switch ยังใช้ในการถอดค่า associate value จาก Enum
Last updated