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

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

作者: 文子飞_ | 来源:发表于2020-12-19 16:32 被阅读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
}

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/rercnktx.html