一、模式
1、什么是模式?
- 模式是用于匹配的规则,比如switch的case、捕捉错误的catch、if\gurad\while\for语句的条件等
2、Swift中的模式有
通配符模式、标识符模式、值绑定模式、元祖模式、枚举case模式、可选模式、类型转换模式、表达式模式。
二、模式详解
1、通配符模式
- _ 匹配任何值
- _? 匹配非nil值
2、标识符模式
- 给对应的变量、常量名赋值
var name = "rose"
let sex = "man"
3、值绑定模式
let point = (3,2)
switch point{
case let(x,y):
print("The point is at \(x) , \(y)")
}
4、元组模式
let point = [(0,0),(1,0),(2,0)]
for (x,_) in point{
print(x)
}
var scores = ["Jack": 98,"rose": 100,"Jim": 80]
for (name,score) in scores{
print(name,score)
}
5、枚举Case模式(Enumeration Case Pattern)
- if case 语句等价于只有一个case的switch语句
let age = 2
if case 0...9 = age{
print("在[0,9]范围之间")
}
guard case 0...9 = age else { return }
switch age{
case 0...9: print("在[0,9]范围之间")
default : break
}
6、可选模式(Optional Pattern)
let age: [Int?] = [nil,2,3,nil,8]
for case let age? in ages{
print(age)
}
for item in ages{
if let age = item {
print(age)
}
}
func check (_ num: Int?){
switch num{
case 2?: print(2)
case 3?: print(3)
case _?: print("other")
case _: print("nil")
}
}
check(4)
check(nil)
7、类型转换模式(Type-Caseing Pattern)
let num: Any = 6
switch num {
case is Int:
// 编译器依然认为num是Any类型
print("is Int", num)
//case let n as Int:
// print("as Int", n + 1)
default:
break
}
class Animal {
func eat() {
print(type(of: self), "eat")
}
}
8、表达式模式
- 表达式模式用在case中
let point = (1, 2)
switch point {
case (0, 0):
print("(0, 0) is at the origin.")
case (-2...2, -2...2):
print("(\(point.0), \(point.1)) is near the origin.")
default:
print("The point is at (\(point.0), \(point.1)).")
} // (1, 2) is near the origin.
9、自定义表达式模式
- 可以通过重载运算符,自定义表达式模式的匹配规则。
struct Student {
var score = 0, name = ""
static func ~= (pattern: Int, value: Student) -> Bool { value.score >= pattern }
static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool { pattern.contains(value.score) } static func ~= (pattern: Range<Int>, value: Student) -> Bool { pattern.contains(value.score) }
}
var stu = Student(score: 75, name: "Jack") switch stu {
case 100: print(">= 100")
case 90: print(">= 90")
case 80..<90: print("[80, 90)") case 60...79: print("[60, 79]") case 0: print(">= 0")
default: break
} // [60, 79]
if case 60 = stu {
print(">= 60")
} // >= 60
var info = (Student(score: 70, name: "Jack"), "及格") switch info {
case let (60, text): print(text)
default: break
} // 及格
10、where
- 可以使用where作为模式匹配增加匹配条件
var data = (10, "Jack")
switch data {
case let (age, _) where age > 10:
print(data.1, "age>10") case let (age, _) where age > 0:
print(data.1, "age>0") default: break
}
protocol Stackable {
associatedtype Element
}
protocol Container {
associatedtype Stack :
Stackable where Stack.Element : Equatable
}
var ages = [10, 20, 44, 23, 55]
for age in ages where age > 30 {
print(age)
} // 44 55
func equal<S1: Stackable, S2: Stackable>(_ s1: S1, _ s2: S2) -> Bool where S1.Element == S2.Element, S1.Element : Hashable {
return false
}
extension Container where Self.Stack.Element : Hashable {}