Swift: Decision Statements

Programming

Swift: Decision Statements

9 เดือนที่ผ่านมา

1 min read

ในการเขียนโปรแกรมแน่นอนว่าต้องมีการตัดสินใจ คือถ้าเงื่อนไขนี้เป็นจริง จะให้ทำอะไร และถ้าเท็จจะให้ทำอะไร เราลองมาดูในภาษา Swift กันว่าจะมีการใช้ยังไงบ้าง

If Statement

อย่างง่ายๆ สุดก็คงจะเป็นการใช้ if else โดยบล็อคแรกคือเงื่อนไขที่เป็นจริง และ else คือเงื่อนไขเป็นเท็จ

let age = 25
 
if age >= 18 {
    print("You are eligible to vote.")
} else {
    print("You are not eligible to vote.")
}

Switch Statement

ในบางครั้งถ้าเงื่อนไขเยอะๆ การใช้ Switch ก็จะทำให้ code ของเราอ่านง่ายขึ้น

let dayOfWeek = "Monday"
 
switch dayOfWeek {
case "Monday":
    print("It's the start of the workweek.")
case "Friday":
    print("It's almost the weekend!")
default:
    print("It's a regular day.")
}

Guard Statement

guard จะใช้ดักเงื่อนไขที่เป็นเท็จ ถึงจะทำงานในบล็อค การนำมาใช้ก็อย่างเช่น นำมาใช้ร่วมกับ Optionals

func divide(a: Int, b: Int) {
    guard b != 0 else {
        print("Cannot divide by zero.")
        return
    }
 
    let result = a / b
    print("Result: \(result)")
}

Tags:

Swift