代码之家  ›  专栏  ›  技术社区  ›  J. Doe

Swift不调用具有关联类型的协议扩展函数中的重写类var

  •  1
  • J. Doe  · 技术社区  · 6 年前

    这是我尽量减少的代码:

    protocol LengthValidater {
        static var minLength: Int { get }
    }
    
    protocol Validater: LengthValidater {
        associatedtype ValidateType
    
        static func generateValue() -> ValidateType
    }
    
    extension Validater {
        static func generate() {
            print(Self.minLength) // prints correctly
            generateValue()
        }
    }
    
    protocol TextValidateable: Validater where ValidateType == String {}
    
    extension TextValidateable {
    
        static func generateValue() -> String {
            print(Self.minLength)
            return ""
        }
    
    }
    
    class TextValidater: TextValidateable {
        class var minLength: Int {
            fatalError()
        }
    }
    
    class UserIdentifier: TextValidater {
        override class var minLength: Int {
            return 10
        }
    }
    

    打电话 UserIdentifier.generate() 会使应用程序崩溃,但显然不应该,因为它应该使用动态调度并调用重写的 class var 删除关联类型和/或返回类型时 generateValue() ,它不会崩溃。

    0 回复  |  直到 6 年前