1. 程式人生 > >swift 學習記錄(二)

swift 學習記錄(二)

在switch case中,每個case分支的statements不需要用{ }包含,例如

(1)

let oneSring: String = "abc"
switch oneSring {
case "abc":
{
    print("The String is oneSring")
    let bbb = 100
    print(bbb)
    print("The String is qqq")
    print("The String is www")
    print("The String is eee")
    print("The String is sss")
    print("The String is DDD")
}
case "A":
    print("The String is A")
default:
    print("Not find String")
}

在第一個case分支,會報錯:

<stdin>:17:1: error: braced block of statements is an unused closure { ^ <stdin>:17:1: error: expression resolves to an unused function { ^

(2)每個case分支如果有多條語句,直接換行寫就可以了,

let oneSring: String = "abc"
switch oneSring {
case "abc":
    print("The String is oneSring")
    let bbb = 100
    print(bbb)
    print("The String is qqq")
    print("The String is www")
    print("The String is eee")
    print("The String is sss")
    print("The String is DDD")
case "A":
    print("The String is A")
default:
    print("Not find String")
}

輸出結果為:

The String is oneSring 100 The String is qqq The String is www The String is eee The String is sss The String is DDD