59
技術社區[雲棲]
Swift學習這十二:(續)控製流
// 值綁定(Value Binding)
let anotherPoint = (2, 0)
// 這就是所謂的值綁定,通過值賦給臨時常量或者變量
switch anotherPoint {
case (let x, 0): // 這裏不需要修改x的值,所以聲明為let,即常量
println("on the x-axis with an x value of \(x)")
case (0, let y):
println("on the y-axis with a y value of \(y)")
case let (x, y): // 對於這裏,沒有使用Default,其實這裏這麼寫法就相當於default:
println("somewhere else at (\(x), \(y))")
}
// 使用where語句來檢測額外的條件
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y: // 使用值綁定,要求x與y相等
println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:// 使用值綁定,要求x與-y相等
println("(\(x), \(y)) is on the line x == -y")
case let (x, y):// 使用值綁定,相當於default
println("(\(x), \(y)) is just some arbitrary point")
}
/*
continue
break
falthrough
return
*/
// continue、break、return跟C、OC中的continue、break、return是一樣的
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for c in puzzleInput {
switch c {
case "a", "e", "i", "o", "u", "":// 相當於遇到這幾種字符就會就會繼續循環而不往下執行
continue
default:
puzzleOutput += c
}
}
let numberSymbol: Character = "三"
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "一":
possibleIntegerValue = 1
case "2", "二"
default:
break
}
let integerToDescribe = 5
var descripton = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 9, 11, 13, 17, 19:
descripton += "a prime number, and also"
falthrough // 加上falthrough,就會繼續往下執行,執行default這裏的語句
default:
descripton += " an integer"
}
// print: The number 5 is a prime number, and also an integer
// 可以給循環添加標簽
var integerValue = 0
let count = 10
GameLoopLabel: while integerValue < count {
switch integerValue {
case integerValue % 2 == 0:
break GameLoopLabel // 調用此語句後,就退出了while循環
case let inValue where (inValue > 5 && inValue % 2 != 0):
continue GameLoopLabel
default:
println("run default")
break GameLoopLabel
}
}
最後更新:2017-04-03 07:56:55