Control Transfer Statements คือ คำสั่งที่ใช้เปลี่ยนลำดับการทำงานของโค้ดที่เราเขียน ในภาษา Swift มี Control Transfer Statements อยู่ 5 แบบ
- break
- continue
- fallthrough
- return
- throw
พื้นฐานของ Control Transfer Statements ที่ใช้บ่อยๆ คงไม่พ้น break, continue ในบทความนี้ เราจะมาเจาะลึกไปที่ 2 ตัวนี้กันครับ
Continue
continue ถูกใช้เพื่อบอกให้ loop หยุดและเริ่มต้นรอบใหม่อีกครั้ง ดังนั้น continue จึงถูกนำมาใช้กับ for - in , while, repeat - while
ตัวอย่างการใช้ Continue ภายใน Loop
var number = 1
while number < 200 {
if (number % 13 == 0){ // หาร 13 ลงตัว
number = number + 1
continue // ข้ามไปทำงานรอบต่อไป
}
print("\(number) is not divisible by 13.")
number = number + 1;
}
เมื่อเราใส่ continue เข้าไป จากตัวอย่างเมื่อ number เป็นค่าที่ 13 ลงตัว continue จะทำงานและข้ามไปรอบถัดไปเลย โดยคำสั่งที่อยู่ด้านล่าง continue จะไม่ทำงานในรอบนั้น
Break
break ถูกใช้เพื่อออกจาก loop หรือ ออกจาก switch
ตัวอย่างการใช้ Break ภายใน Loop
var number = 1
while number < 200 {
if ((number % 5 == 0) && (number % 7 == 0)) { // หาร 5 และ หาร 7 ลงตัว
print("The first number divisible by both 5 and 7 is \(number)")
break // ออกจาก While
}
number = number + 1
}
เมื่อเราใส่ break เข้าไป จากตัวอย่างเมื่อ number เป็นเลขที่ หารด้วย 5 และ 7 ลงตัว นั้นคือเลข 35 คำสั่ง break จะทำงานและออกจาก While Loop ทันที
ตัวอย่างการใช้ Break ภายใน Switch - Case
var number = 1
switch number {
case 1:
print("number is 1")
break
print("number is positive")
case 2:
print("number is 2")
default:
print("number isn't range.")
}
จากตัวอย่าง คำสั่ง "number is positive" จะไม่ทำงาน เนื่องจากเจอ break แล้ว ออกจาก switch ก่อน