func tsetCase() {
let points = [(1, 0), (2, 1), (3, 0)]
for case (let x, let y) in points {
print(x, y)
}
for case let (x, _) in points {
print(x)
}
for case let (x, 0) in points {
print(x)
}
}
可选模式
let ages: [Int?] = [nil, 1, 2, 3, nil, 8]
for case let age? in ages {
print(age)
}
for item in ages {
if let age = item {
print(age)
}
}
模式匹配
// ~= 是case的方法
extension String {
static func ~= (parttern: (String) -> Bool, value: String) -> Bool {
parttern(value)
}
}
// { $0.hasPrefix(prefix) } 等同于 return { (str: String) -> Bool in str.hasPrefix(prefix) }
// prefix == "123"
// str == "123456"
func hasPrefix(_ prefix: String) -> ((String) -> Bool) {
{ $0.hasPrefix(prefix) }
}
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
{ $0.hasSuffix(suffix) }
}
var fn = hasPrefix("123")
print(fn("123456")) // true
print(fn("41236")) // false
var str = "12346"
switch str {
case hasPrefix("123"): // (String) -> Bool
print("以123开头")
case hasSuffix("123"): // (String) -> Bool
print("以123结尾")
case default:
break
}