1

This is the code I tried to minimize as much as possible:

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
    }
}

Calling UserIdentifier.generate() will crash the app, while it clearly should not since it should use dynamic dispatching and call the overridden class var. When I remove the associated type and/or return type of generateValue(), it does not crash.

Why does it crash?

J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • 2
    You want to use `self` instead of `Self` (so just do `print(minLength)`). Using `Self` as a value in a protocol extension [is a path to madness](https://stackoverflow.com/q/42037852/2976878). – Hamish Dec 07 '18 at 21:29
  • @Hamish O jeez I sure have lots to learn about protocols :) – J. Doe Dec 07 '18 at 22:12

0 Answers0