【Swift】协议式编程使用(利用协议 给系统类扩展功能)

2020-12-19  本文已影响0人  文子飞_

Swift协议式编程使用

利用协议 给系统类扩展功能
func testMethod() {
        let numberCount = "abcdefg1234567".lf.numberCount
        print("numberCount = \(numberCount)")
        String.lf.testStaticMethod()
        
        var mutatingString = "abcdefg1234567"
        mutatingString.lf.testMutatingMethod()
    }

/// 1、写一个前缀类型(Struct)
struct LF<Base> {
    var base: Base
    init(_ base: Base) {
        self.base = base
    }
}

/// 2、定义一个协议,给协议扩展前缀属性(实例属性+类型属性)
protocol LFCommon {}
extension LFCommon {
    var lf: LF<Self> {
        get { LF(self) }
        set {}
    }
    static var lf: LF<Self>.Type {
        get { LF<Self>.self }
        set {}
    }
}


/// 3、给字符串扩展功能
/// 让String拥有LF前缀属性
extension String: LFCommon { }
/// 给String.lf、String().lf前缀扩展功能
extension LF where Base == String {
    
    var numberCount: Int {
        var count: Int = 0
        for c in base where ("0"..."9").contains(c) {
            count += 1
        }
        return count
    }
    
    // 扩展mutating方法,修改结构体。需要重写前缀属性的get{}、set{}方法
    mutating func testMutatingMethod() {}
    
    static func testStaticMethod() {}
    
}
Base:协议
extension NSString: LFCommon {}
/// String、NSString、MSMutableString都遵守了ExpressibleByStringLiteral协议
extension LF where Base: ExpressibleByStringLiteral {
    var numberCount: Int {
        var count: Int = 0
        for c in (base as! String) where ("0"..."9").contains(c) {
            count += 1
        }
        return count
    }
}
Base:类
func testMethod() {
        Person.lf.eat()
        Student.lf.eat()
        
        let person = Person()
        person.lf.run()
        
        let student = Student()
        student.lf.run()
    }

class Person {}
class Student: Person {}

extension Person: LFCommon {}
extension LF where Base: Person {
    func run() {}
    static func eat() {}
}
利用协议,实现类型判断
func testMethod() {
        print(isArrayType([Int].self))
        print(isArrayType([Any].self))
        print(isArrayType(Array<Any>.self))
        print(isArrayType(NSArray.self))
        print(isArrayType(String.self))
    }

protocol ArrayType {}
extension Array: ArrayType {}
extension NSArray: ArrayType {}
func isArrayType(_ type: Any.Type) -> Bool {
    type is ArrayType.Type
}
上一篇下一篇

猜你喜欢

热点阅读