2016-10-02 12:18:59 chankuang2008 阅读数 376
  • Android底层技术:Linux驱动框架与开发

    于此,将框架(Framework)和设计模式(Design Pattern)应用于Linux驱动开发,说明了如何以面向对象、设计模式和框架概念来看待Linux驱动程序的架构。其直接的益处就是:让我们能基于一致的设计理念来结合Android HAL与Linux两层的驱动开发,规划出整体和谐Android-based软硬整合产品架构。

    22350 人正在学习 去看看 高煥堂
/*
把统一复杂的工序、细分成不同的简单工序
能够轻易增加、修改工序
*/

// 药品 复杂产品
class MedicineProduct {
    var p_stName : String = ""
    var p_mNumber : Int = 0
    var p_stPacking : String = ""
    var p_stExpiryDate : String = ""
    var p_stLocation : String = ""
}

// 生产员 抽象建造者
class Builder {
	func buildName() { }
	func getProduct() -> MedicineProduct { 
	    return MedicineProduct()
	}
}

// 阿司匹林 具体建造者
class AspirinProduct : Builder {
	override func buildName() {
		medicineProduct.p_stName = "Aspirin"
		medicineProduct.p_mNumber = 100
		medicineProduct.p_stPacking = "box"
        medicineProduct.p_stExpiryDate = "1 year"
        medicineProduct.p_stLocation = "ZhuHai"
	}
	override func getProduct() -> MedicineProduct {
	    return medicineProduct
	}
	    
    var medicineProduct = MedicineProduct()
}

// 阿司匹林 具体建造者
class ParacetamolProduct : Builder {
	override func buildName() {
		medicineProduct.p_stName = "Paracetamol"
		medicineProduct.p_mNumber = 80
		medicineProduct.p_stPacking = "package"
        medicineProduct.p_stExpiryDate = "2 years"
        medicineProduct.p_stLocation = "ShanZhun"
	}
	override func getProduct() -> MedicineProduct {
	    return medicineProduct
	}
	    
    var medicineProduct = MedicineProduct()
}

// 装货员 指挥者
class Managaer {
    var builder = Builder()
    func Construct(c_concreteBuilder : Builder) -> MedicineProduct {
        builder = c_concreteBuilder
        builder.buildName()
        return builder.getProduct()
    }
}

// 客戶端
let managaer = Managaer()
// 客戶只需要更改药物的建造者、即工厂类、就能完成不同工厂的复杂包装程序
let product = managaer.Construct(c_concreteBuilder: AspirinProduct())
print("Name: \(product.p_stName) Number: \(product.p_mNumber) Packing: \(product.p_stPacking) ExpiryDate: \(product.p_stExpiryDate) Location: \(product.p_stLocation)")

let product2 = managaer.Construct(c_concreteBuilder: ParacetamolProduct())
print("Name: \(product2.p_stName) Number: \(product2.p_mNumber) Packing: \(product2.p_stPacking) ExpiryDate: \(product2.p_stExpiryDate) Location: \(product2.p_stLocation)")

2019-08-03 22:16:39 weixin_42433480 阅读数 18
  • Android底层技术:Linux驱动框架与开发

    于此,将框架(Framework)和设计模式(Design Pattern)应用于Linux驱动开发,说明了如何以面向对象、设计模式和框架概念来看待Linux驱动程序的架构。其直接的益处就是:让我们能基于一致的设计理念来结合Android HAL与Linux两层的驱动开发,规划出整体和谐Android-based软硬整合产品架构。

    22350 人正在学习 去看看 高煥堂

模式(Pattern)

  • 什么是模式?
  • 模式是用于匹配的规则,比如switch的case、捕捉错误的catch、if\guard\while\for语句的条件等
  • Swift中的模式有
  1. 通配符模式(Wildcard Pattern) 
  2. 标识符模式(Identifier Pattern) 
  3. 值绑定模式(Value-Binding Pattern) 
  4. 元组模式(Tuple Pattern) 
  5. 枚举Case模式(Enumeration Case Pattern) 
  6. 可选模式(Optional Pattern) 
  7. 类型转换模式(Type-Casting Pattern) 
  8. 表达式模式(Expression Pattern)

通配符模式(Wildcard Pattern)

  • _ 匹配任何值
  • _? 匹配非nil值
enum Life {
    case human(name: String, age: Int?)
    case animal(name: String, age: Int?)
}

func check(_ life: Life) {
    switch life {
    case .human(let name, _):
        print("human", name)
    case .animal(let name, _?):
        print("animal", name)
    default:
        print("other")
    }
}

check(Life.human(name: "Rose", age: 20)) //human Rose
check(Life.human(name: "Jack", age: nil)) //human Jack
check(Life.animal(name: "Dog", age: 5)) //animal Dog
check(Life.animal(name: "Cat", age: nil)) //other

check(.human(name: "Rose", age: 20)) //human Rose
check(.human(name: "Jack", age: nil)) //human Jack
check(.animal(name: "Dog", age: 5)) //animal Dog
check(.animal(name: "Cat", age: nil)) //other

标识符模式(Identifier Pattern)

  • 给对应的变量、常量名赋值
var age = 10
let name = "jack"

值绑定模式(Value-Binding Pattern)

把元祖中3和2的值分别绑定给x和y:

 


元组模式(Tuple Pattern)

let points = [(0, 0), (1, 0), (2, 0)]
for (x, _) in points {
    print(x)
}

let name: String? = "Jack"
let age = 18
let info: Any = [1,2]
switch (name, age, info) {
case (_?, _, _ as String):
    print("case")
default:
    print("default")
} //输出default

var scores = ["jack": 98, "Rose": 100, "Kate": 86]
for (name, score) in scores {
    print((name, score))
}
//输出:
//("jack", 98)
//("Rose", 100)
//("Kate", 86)

枚举Case模式(Enumeration Case Pattern)

  • if case语句等价于只有一个case的switch语句
let age = 2

//原来的写法
if age >= 0 && age <= 9 {
    print("[0, 9]") //[0, 9]
}

//枚举case模式:看age里是否有0到9的数字,如果匹配,进入{ }
if case 0...9 = age {
    print("[0, 9]") //[0, 9]
}

guard case 0...9 = age else { return }
print("[0, 9]")

switch age {
case 0...9: print("[0, 9]")
default: break
}//[0, 9]

let ages: [Int?] = [2, 3, nil, 5]
for case nil in ages {
    print("有nil值")
    break
} //有nil值

let points = [(1, 0), (2, 1), (3, 0)]
for case let (x, 0) in points {
    print(x)
} // 1 3

可选模式(Optional Pattern)

//.some(let x)等同于 let x?
let age: Int? = 42
if case .some(let x) = age {print(x)}
if case let x? = age { print(x)} //age为非空则匹配成功,并且解包给x

let ages: [Int?] = [nil, 2, 3, nil, 5]
//age为不为nil的可选型,符合则自动解包
for case let age? in ages {
    print(age)
}

//下面的代码与上面的代码实现效果一致
for item in ages {
    //item如果为非空可选,则自动解包赋值给age
    if let age = item {
        print(age)
    }
}

 

func check(_ num: Int?) {
    switch num {
    case 2?: print("2") //如果num为非nil的可选型2,输出2
    case 4?: print("4")
    case 6?: print("6")
    case _?: print("other")
    case _: print("nil")
    }
}

check(4) //4
check(8) //other
check(nil) //nil

类型转换模式(Type- Casting Pattern)

 

let num = 6
switch num {
case is Int:
    //num是Int类型
    print("is Int", num)
default:
    break
} //输出 is Int 6

let num1: Any = 6
switch num1 {
case is Int:
    //num依然是Any类型,但是Any是任意类型,可以认为是Int,所以会进入这个case
    print("is Int", num)
default:
    break
} //输出 is Int 6
let num: Any = 6
switch num {
    //num如果可以转换为Int类型,就把转换后的值给n
case let n as Int:
    //num依然是Any类型,只是它转换后的n是Int类型
    print("as Int", n + 1)
default:
    break
} // 输出 as Int 7

实际用例:

class Animal {
    func eat() {print(type(of: self), "eat")}
}

class Dog: Animal {
    func run() {
        print(type(of: self), "run")
    }
}

class Cat: Animal {
    func jump() {
        print(type(of: self), "jump")
    }
}

func check(_ animal: Animal) {
    switch animal {
        //看能否吧animal转换为Dog类型,如果可以,则把转换后的值给dog变量
    case let dog as Dog:
        dog.eat()
        dog.run()
    case is Cat:
        //编译器认为现在的animal是Animal类型,只能调用animal的eat()方法,不能调用Cat的jump方法
        animal.eat()
        //这里的animal不能直接调用Cat的jump()方法,除非强制转换成Cat类型
//        (animal as? Cat)?.jump()
    default:
        break
    }
}

check(Dog())
//Dog eat
//Dog run

check(Cat())
//typeof最终看调用的实际对象类型,所以是Cat类型
//Cat eat

表达式模式(Expression Pattern)

  • 表达模式用在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.

通果反汇编运算,我们可以看到这实际上是通过~=这个符号实现的表达式匹配,所以想要自定义表达式模式匹配,需要重载~=这个运算符


自定义表达式模式

  • 可以通过重载运算符,自定义表达式模式的匹配规则
struct Student {
    var score = 0, name = ""
    //pattern是case后的值
    //value是switch后的值
    static func ~= (pattern: Int, value: Student) -> Bool {
        return value.score >= pattern
    }
    static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool {
        return pattern.contains(value.score)
    }
    static func ~= (pattern: Range<Int>, value: Student) -> Bool {
        return 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 {
//如下代码表示Student(score: 70, name: "Jack")和60进行匹配,"及格"和text进行匹配,当score大于60则为true,走print(text)代码
case let (60, text): print(text)
default: break
} //输出: 及格

先列举一个String判断开头结尾是什么的复杂结构的常规代码:

//prefix == "21"
//str == "123456"
func hasPerfix(_ prefix: String) -> ((String) -> Bool) {
    return {
        (str: String) -> Bool in
        str.hasPrefix(prefix)
    }
}

//suffix == "456"
//str == "123456"
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
    return {
        (str: String) -> Bool in
        str.hasSuffix(suffix)
    }
}

var fn = hasPerfix("12")
print(fn("123456")) //true
var fn1 = hasSuffix("456")
print(fn1("123456")) //true

接下来用重载运算符的方式,自定义表达式模式的匹配规则:

extension String {
    static func ~= (pattern: (String) -> Bool, value: String) -> Bool {
       return pattern(value)
    }
}

func hasPerfix(_ prefix: String) -> ((String) -> Bool) {
//$0表示第一个参数
   return { $0.hasPrefix(prefix) }
}
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
    return { $0.hasSuffix(suffix) }
}

var str = "123456"
switch str {
case hasPerfix("12"), hasSuffix("456"):
    print("以12开头或者以456结尾")
default:
    break
} // 输出:以12开头或者以456结尾

//var str = "123456"
//switch str {
//case hasPerfix("12"):
//    print("以12开头")
//case hasSuffix("456"):
//    print("以456结尾")
//default:
//    break
//} //输出:以12开头

类似上面的例子:

 

  • 接下来列举一个重载运算符实现新的运算符功能的例子:

1.  原始写法:

func greaterThan(_ num: Int) -> (Int) -> Bool {
    return {
        (i: Int) -> Bool in
        return i > num
    }
}

var fn = greaterThan(5)
print(fn(10)) //true

2.  自定义表达模式的匹配原则:

extension Int {
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
        return pattern(value)
    }
}

func greaterThan1(_ num: Int) -> (Int) -> Bool {
    return { $0 > num }
}

var age = 10

switch age {
case greaterThan(5):
    print(age, "大于5")
default: break
} // 输出:10 大于5

3.  重写比较运算符

extension Int {
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
        return pattern(value)
    }
}

prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=
prefix func ~> (_ i: Int) -> ((Int) -> Bool) { return { $0 > i} }
prefix func ~>= (_ i: Int) -> ((Int) -> Bool) { return { $0 >= i} }
prefix func ~< (_ i: Int) -> ((Int) -> Bool) { return { $0 < i} }
prefix func ~<= (_ i: Int) -> ((Int) -> Bool) { return { $0 <= i} }

var age = 9
switch age {
case ~>=0:
    print("1")
case ~>10:
print("2")
default:
     break
} //输出:1
  • 在列举一个简单奇偶数判定的例子
func isEven(_ i: Int) -> Bool { return i % 2 == 0}
func isOdd(_ i: Int) -> Bool { return i % 2 != 0}

extension Int {
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
       return pattern(value)
    }
}

var age = 11
switch age {
case isEven:
    print("偶数")
case isOdd:
    print("奇数")
default:
    print("其他")
} // 输出: 奇数

Where

  • 可以使用where为模式匹配增加条件

switch case中的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
} //jack age>0

for循环中的where用例:

var ages = [10, 20 , 44, 23, 55]
for age in ages where  age > 30 {
    print(age)
} //44 55

协议中关联类型的where用例:

protocol Stackable { associatedtype Element}
protocol Container {
    associatedtype Stack : Stackable where Stack.Element : Equatable
}

泛型中的where用例:

func equal<S1: Stackable, S2:Stackable>(_ s1:S1, _s2:S2) -> Bool where S1.Element == S2.Element, S1.Element : Hashable{
    return false
}

扩展中的where用例:

extension Container where Self.Stack.Element : Hashable { }

 

 

 

 

 

 

2016-07-30 16:48:53 chankuang2008 阅读数 275
  • Android底层技术:Linux驱动框架与开发

    于此,将框架(Framework)和设计模式(Design Pattern)应用于Linux驱动开发,说明了如何以面向对象、设计模式和框架概念来看待Linux驱动程序的架构。其直接的益处就是:让我们能基于一致的设计理念来结合Android HAL与Linux两层的驱动开发,规划出整体和谐Android-based软硬整合产品架构。

    22350 人正在学习 去看看 高煥堂
/*
工厂方法模式 - 创建物件    
厂商现有Aspirin的生产线、若想添加Paracetamol生产线、就能用工厂方法模式。    
Aspirin和Paracetamol有各自的物件、抽像物件、工厂、抽象工厂。    
在不修改原有程序下增加物件。    
Java是用interface和implement来表达物件、抽像物件的关系。    
Swift是用protocol和继承来表达物件、抽像物件的关系。    
*/    
    
import Foundation    
    
protocol MedicineProduct {    
    var p_stName : String { get set }    
    var p_stFormula : String { get set }    
    var p_douDensity : Double { get set }    
    var p_mCAS: Int { get set }    
    var p_stTreatment : String { get set }    
        
    func getProduct() -> String    
}    
   
protocol MedicineFactory {    
    func createMedicine() -> MedicineProduct    
}    
    
class AspirinProduct : MedicineProduct {    
    var p_stName : String = "Aspirin"    
    var p_stFormula : String = "C9H8O4"    
    var p_douDensity : Double = 1.40    
    var p_mCAS: Int = 50782    
    var p_stTreatment : String = "pain, fever, inflammation"    
        
    func getProduct() -> String {    
        return "\(p_stName), Treatment are \(p_stTreatment),  Formula is \(p_stFormula), Density is \(p_douDensity)g/cm3, CAS number is \(p_mCAS)."    
    }    
}    
    
class ParacetamolProduct : MedicineProduct {    
    var p_stName : String = "Paracetamol"    
    var p_stFormula : String = "C8H9NO2"    
    var p_douDensity : Double = 1.263    
    var p_mCAS: Int = 103902    
    var p_stTreatment : String = "headache, muscle aches, arthritis, backache, toothaches, colds, and fevers"    
        
    func getProduct() -> String {    
        return "\(p_stName), Treatment are \(p_stTreatment),  Formula is \(p_stFormula), Density is \(p_douDensity)g/cm3, CAS number is \(p_mCAS)."    
    }    
}    
    
class AspirinProductFactory : MedicineFactory {    
    static let sharedInstance:AspirinProductFactory = AspirinProductFactory()    
    func createMedicine() -> MedicineProduct {    
        return AspirinProduct()    
    }    
}    
    
class ParacetamolProductFactory : MedicineFactory {    
    static let sharedInstance:ParacetamolProductFactory = ParacetamolProductFactory()    
    func createMedicine() -> MedicineProduct {    
        return ParacetamolProduct()    
    }    
}    
    
let Aspirinproduct1: MedicineProduct = AspirinProductFactory.sharedInstance.createMedicine()    
print(Aspirinproduct1.getProduct())    
    
print("")    
    
let Paracetamolproduct1: MedicineProduct = ParacetamolProductFactory.sharedInstance.createMedicine()    
print(Paracetamolproduct1.getProduct())

2019-03-27 15:52:20 u011248221 阅读数 56
  • Android底层技术:Linux驱动框架与开发

    于此,将框架(Framework)和设计模式(Design Pattern)应用于Linux驱动开发,说明了如何以面向对象、设计模式和框架概念来看待Linux驱动程序的架构。其直接的益处就是:让我们能基于一致的设计理念来结合Android HAL与Linux两层的驱动开发,规划出整体和谐Android-based软硬整合产品架构。

    22350 人正在学习 去看看 高煥堂

抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。

下面是参照菜鸟教程里的Java实例写的swift版本,问底会贴出原文链接。

1、为形状创建一个接口。

protocol Shape {
    func draw()
}

2、创建实现接口的实体类。

class Rectangle: Shape {
    func draw() {
        print("Inside Rectangle::draw() method.")
    }
}

class Square: Shape {
    func draw() {
        print("Inside Square::draaw() method.")
    }
}

class Circle: Shape {
    func draw() {
        print("Inside Circle::draw() method.")
    }
}

3、为颜色创建一个接口。

protocol Color {
    func fill()
}

4、创建实现接口的实体类。

class Red: Color {
    func fill() {
        print("Inside Red::fill() method.")
    }
}

class Green: Color {
    func fill() {
        print("Inside Green::fill() method.")
    }
}

class Blue: Color {
    func fill() {
        print("Inside Blue::fill() method.")
    }
}

5、为 Color 和 Shape 对象创建抽象类来获取工厂。

protocol AbstractFactory {
    func getColor(color:String) -> Color?
    func getShape(shape:String) -> Shape?
}

6、创建扩展了 AbstractFactory 的工厂类,基于给定的信息生成实体类的对象。

class ShapeFactory: AbstractFactory {
    
    func getShape(shape: String) -> Shape? {
        if shape.isEmpty {
            return nil
        }
        if shape == "CIRCLE" {
            return Circle.init()
        } else if shape == "RECTANGLE" {
            return Rectangle.init()
        } else if shape == "SQUARE" {
            return Square.init()
        } else {
            return nil
        }
    }
    
    func getColor(color: String) -> Color? {
        return nil
    }
}

class ColorFactory: AbstractFactory {
    func getColor(color: String) -> Color? {
        if color.isEmpty {
            return nil
        }
        if color == "RED" {
            return Red.init()
        } else if color == "GREEN" {
            return Green.init()
        } else if color == "BLUE" {
            return Blue.init()
        } else {
            return nil
        }
    }
    
    func getShape(shape: String) -> Shape? {
        return nil
    }
}

7、创建一个工厂创造器/生成器类,通过传递形状或颜色信息来获取工厂。

class FactoryProducer: NSObject {
    class func getFactory(choice: String) -> AbstractFactory? {
        if choice == "SHAPE" {
            return ShapeFactory.init()
        } else if choice == "COLOR" {
            return ColorFactory.init()
        }
        return nil
    }
}

8、使用 FactoryProducer 来获取 AbstractFactory,通过传递类型信息来获取实体类的对象。

// 获取形状工厂
let shapeFactory = FactoryProducer.getFactory(choice: "SHAPE")!
// 获取形状为 Circle 的对象
let shape1 = shapeFactory.getShape(shape: "CIRCLE")!
// 调用 Circle 的 draw 方法
shape1.draw()
// 获取形状为 Rectangle 的对象
let shape2 = shapeFactory.getShape(shape: "RECTANGLE")!
// 调用 Rectangle 的 draw 方法
shape2.draw()
// 获取形状为 Square 的对象
let shape3 = shapeFactory.getShape(shape: "SQUARE")!
// 调用 Square 的 draw 方法
shape3.draw()

// 获取颜色工厂
let colorFactory = FactoryProducer.getFactory(choice: "COLOR")!
// 获取颜色为 Red 的对象
let color1 = colorFactory.getColor(color: "RED")!
// 调用 Red 的 fill 方法
color1.fill()
// 获取颜色为 Green 的对象
let color2 = colorFactory.getColor(color: "GREEN")!
// 调用 Green 的 fill 方法
color2.fill()
// 获取颜色为 blue 的对象
let color3 = colorFactory.getColor(color: "BLUE")!
// 调用 blue 的 fill 方法
color3.fill()

源代码
菜鸟教程Java版

2019-09-18 16:38:22 songzhuo1991 阅读数 23
  • Android底层技术:Linux驱动框架与开发

    于此,将框架(Framework)和设计模式(Design Pattern)应用于Linux驱动开发,说明了如何以面向对象、设计模式和框架概念来看待Linux驱动程序的架构。其直接的益处就是:让我们能基于一致的设计理念来结合Android HAL与Linux两层的驱动开发,规划出整体和谐Android-based软硬整合产品架构。

    22350 人正在学习 去看看 高煥堂
  • 什么是模式?

  • 模式是用于匹配的规则,比如switch的case、捕捉错误的catch、if\guard\while\for语句的条件等

  • Swift中的模式有:

  1. 通配符模式(Wildcard Pattern)
  2. 标识符模式(Identifier Pattern)
  3. 值绑定模式(Value-Binding Pattern)
  4. 元组模式(Tuple Pattern)
  5. 枚举Case模式(Enumeration Case Pattern)
  6. 可选模式(Optional Pattern)
  7. 类型转换模式(Type-Casting Pattern)
  8. 表达式模式(Expression Pattern)

通配符模式(Wildcard Pattern)

  • _ 匹配任何值
  • _? 匹配非nil值
enum Life {
    case human(name: String, age: Int?)
    case animal(name: String, age: Int?)
}
func check(_ life: Life) {
    switch life {
        case .human(let name, _):
            print("human", name)
        case .animal(let name, _?):
            print("animal", name)
        default:
            print("other")
    }
}
check(.human(name: "Rose", age: 20)) // human Rose
check(.human(name: "Jack", age: nil)) // human Jack
check(.animal(name: "Dog", age: 5)) // animal Dog
check(.animal(name: "Cat", age: nil)) // other
var num: Int? = 10
switch num {
    case let v?:
        print(v)
    case nil: 
        print("nil")
}

标识符模式( Identifier Pattern)

  • 给对应的变量、常量名赋值
var age = 10
let name = "Jack"

值绑定模式( Value-Binding Pattern)

let point = (3, 2)
switch point {
    case let (x, y):
        print("The point is at (\(x),\(y)).")
}

元组模式( Tuple Pattern)

let points = [(0, 0), (1, 0), (2, 0)]
for (x, _) in points {
    print(x)
}
let name: String? = "jack"
let age = 18
let info: Any = [1, 2]
switch (name, age, info) {
    case (_?, _, _ as String):
        print("case")
    default:
        print("default")
} // default
var scores = ["jack": 98, "rose": 100, "kate":86]
for (name, score) in scores {
    print(name, score)
}

枚举case模式( Enumeration Case Pattern)

  • if case语句等价于只有1个case的switch语句
let age = 2
// 原来的写法
if age >= 0 && age <= 9 {
    print("[0, 9]")
}
// 枚举Case模式
if case 0...9 = age {
    print("[0, 9]")
}
guard case 0...9 = age else { return }
print("[0, 9]")
switch age {
    case 0...9: print("[0, 9]")
    default: break
}
let ages: [Int?] = [2, 3, nil, 5]
for case nil in ages {
    print("有nil值")
    break
} // 有nil值


可选模式(Optional Pattern)

let age: Int? = 42
if case .some(let x) = age { print(x) }
if case let x? = age { print(x) }
let ages: [Int?] = [nil, 2, 3, nil, 5]
for case let age? in ages {
    print(age)
} // 2 3 5
let ages: [Int?] = [nil, 2, 4, 5]
for item in ages {
    if let age = item {
        print(age)
    }
} // 跟上面的for,效果等价的
func check(_ num: Int?) {
    switch num {
        case 2?: print("2")
        case 4?: print("4")
        case 6?: print("6")
        case _?: print("other")
        case _: print("nil")
    }
}
check(4) // 4
check(8) // other
check(nil) // nil

类型转换模式(Type-Casting 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")
    }
} 
class Dog: Animal { 
    func run() { 
        print(type(of: self), "run")
    }
} 
class Cat: Animal { 
    func jump() { 
        print(type(of: self), "jump")
    }
} 
func check(_ animal: Animal) {
    switch animal {
        case let dog as Dog:
            dog.eat()
            dog.run()
        case is Cat:
            animal.eat()
        default: break    
    }
}
// Dog eat
// Dog run
check(Dog())
// Cat eat
//check(Cat())

表达式模式(Expression Pattern)

  • 表达式模式用在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)) isnear the origin.")
    default:
        print("The point is at (\(point.0),\(point.1)).")
} // (1, 2) is near the origin

自定义模式(Expression Pattern)

  • 可以通过重载运算符,自定义表达式模式的匹配规则
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")
}
var info = (Student(score: 70, name: "Jack"), "及格")
switch info {
    case let (60, text): print(text)
    default: break
} // 及格

extension String {
    static func ~= (pattern: (String) -> Bool, value: String) -> Bool {
        pattern(value)
    }
}
func hasPrefix(_ s:String) -> ((String) -> Bool) { { $0.hasPrefix(s) } }
func hasSuffix(_ s:String) -> ((String) -> Bool) { { $0.hasSuffix(s) } }
var str = "jack"
switch str {
    case hasPrefix("j"), hasSuffix("k"):
        print("以j开头,或者以k结尾")
    default: break
} // 以j开头,或者以k结尾

func isEven(_ i: Int) -> Bool { i % 2 == 0 }
func isOdd(_ i: Int) -> Bool { i % 2 != 0 }
extension Int {
    static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
        pattern(value)
    }
}
var age = 9
switch age {
    case isEven:
        print("偶数")
    case isOdd:
        print("奇数")
    default:
        print("其他")
}
prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=
prefix func ~> (_ i: Int) -> ((Int) -> Bool) { { $0 > i } }
prefix func ~>= (_ i: Int) -> ((Int) -> Bool) { { $0 >= i } }
prefix func ~< (_ i: Int) -> ((Int) -> Bool) { { $0 < i } }
prefix func ~<= (_ i: Int) -> ((Int) -> Bool) { { $0 <= i } }
var age = 0
switch age {
    case ~>=0:
        print("1")
    case ~>10:, ~<20
        print("2")
    default: break
} // [0, 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
}
var ages = [10, 20, 44, 23, 55]
for age in ages where age > 30 {
    print(age)
} // 44 55
protocol Stackable { associatedtype Element }
protocol Container {
    associatedtype Stack: Stackble where Stack.Element: Equtable
}
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 { }
没有更多推荐了,返回首页