🔹switch

🚧 施工中

Swiftflow controlbranch ⟩ switch

unlabeled 'break' is only allowed inside a loop or switch. ( 👉 see: for...in vs. forEach )

let value: Int? = 42

// switch on Optional
switch value {
    case .some(let n): print("有值:\(n)")
    case .none: print("無值")
}

// switch on Optional
switch value {

    // ⭐️ `case let n?` 相當於 `case .some(let n)`
    case let n?: print("有值:\(n)") 
    
    // ⭐️ where clause
    case let n? where n > 40: print("值大於 40:\(n)")
       
    // ⭐️ `case nil` 相當於 `case .none`
    case nil: print("無值")
    
    // ⭐️ 判斷是否為某特定值時,直接寫就可以
    case 42: print("值是 42")
}

// switch on tuple of optionals
switch (optionalA, optionalB){
    case (.some, nil):     // ⭐️ 不想綁定變數時:用 `.some`
    case (nil, .some):     // ...
    case (let x?, let y?): // ⭐️ 綁定變數時:用 `let x?`
    case (nil, nil):       //
}

Last updated