基本控制
var x = 0;
repeat {
x += 1
print(x)
if x > 3 {
continue
}
if x > 4 {
break
}
} while x < 5
let p1 = (12, 13)
if case (12, 13) = p1 {
print("equal")
}
//value binding
let p2 = "hello"
switch p1 {
case (0, 0):
print("=====")
case is String:
print("is String")
default:
break
}
defer {
print("Must do something")
}
let skills = ["JS", nil, "C", nil]
for case let skill? in skills {
print("Get \(skill) ")
}
let percentage = 0.5
//Range 匹配
if case 0...1 = percentage {
print("In range")
}
let name = "FPP"
let age = 34
if case ("FPP", 34) = (name, age) {
print("Match user")
}
自定义约等
//样式匹配背后的准则
//Range ~= T 由系统实现了, 对应到了 if case 0...1 = percentage
//打印 ~ = 就是约等
func ~=<T>(value: T, pattern: ClosedRange<T>) -> Bool {
return pattern.contains(value)
}
if case 0.5 = 0.0...1.0 {
print("自定义约等")
}