Skip to content

Instantly share code, notes, and snippets.

@KingOfBrian
Created December 5, 2016 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KingOfBrian/9739d45c20b6bc8daea4a288c3e35bef to your computer and use it in GitHub Desktop.
Save KingOfBrian/9739d45c20b6bc8daea4a288c3e35bef to your computer and use it in GitHub Desktop.
Specialization incorrectly uses the default implementation
protocol Factory {
associatedtype Value = Self
static func make() -> Value
}
extension Factory {
static func make() -> Value {
fatalError("In default static implementation")
}
}
struct EmptyFactory: Factory {
static func make() -> EmptyFactory {
return self.init()
}
}
struct GenericFactory<T, V>: Factory {
let variableT: T? = nil
let variableV: V? = nil
static func make() -> GenericFactory<T, V> {
return self.init()
}
}
extension Dictionary: Factory {
static func make() -> Dictionary<Key, Value> {
return self.init()
}
}
func testSpecialization<F: Factory>(type: F.Type) {
let v = F.make()
print(v)
}
print(Dictionary<String, String>.make()) // Uses dictionary implementation
testSpecialization(type: EmptyFactory.self) // Uses EmptyFactory Implementation
testSpecialization(type: GenericFactory<String, String>.self) // Uses GenericFactory<String> Implementation
// This invocation is the bug. It will use the protocol's default implementation
testSpecialization(type: Dictionary<String, String>.self) // Uses default implementation
// Rename Factory.Value to Factory.Value2 and the default implementation is correctly found.
// And curiously enough, this does not have any issue.
struct GenericFactoryWithValueConflict<T, Value>: Factory {
let variableT: T? = nil
let variableV: Value? = nil
static func make() -> GenericFactoryWithValueConflict<T, Value> {
return self.init()
}
}
testSpecialization(type: GenericFactoryWithValueConflict<String, String>.self) // Uses GenericFactoryWithValueConflict<String, String> Implementation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment