Skip to content

Instantly share code, notes, and snippets.

@nvh
Last active August 24, 2016 21:12
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 nvh/576485900719b9b5046ba9027130390c to your computer and use it in GitHub Desktop.
Save nvh/576485900719b9b5046ba9027130390c to your computer and use it in GitHub Desktop.
import Foundation
class Animal: NSObject {
}
protocol Named {
init(name: String)
}
protocol AnimalSpecification {
associatedtype AnimalType: Animal
}
//This workaround doesn't add any extra type information, but fixes the problem
func workaround<AnimalType>(name: String) -> AnimalType where AnimalType: Named {
return AnimalType(name: name)
}
extension AnimalSpecification where AnimalType: Named {
func animal(named name: String) -> AnimalType {
return workaround(name: name)
}
}
class Dog: Animal, Named {
let name: String
required init(name: String) {
self.name = name
super.init()
}
}
struct Kennel: AnimalSpecification {
typealias AnimalType = Dog
}
let kennel = Kennel()
kennel.animal(named: "Brian")
import Foundation
// Removing the subclassing from NSObject fixes the problem
class Animal: NSObject {
}
protocol Named {
init(name: String)
}
protocol AnimalSpecification {
associatedtype AnimalType: Animal
}
extension AnimalSpecification where AnimalType: Named {
func animal(named name: String) -> AnimalType {
return AnimalType(name: name)
}
}
class Dog: Animal, Named {
let name: String
required init(name: String) {
self.name = name
super.init()
}
}
struct Kennel: AnimalSpecification {
typealias AnimalType = Dog
}
let kennel = Kennel()
kennel.animal(named: "Brian")
@nvh
Copy link
Author

nvh commented Aug 24, 2016

This produces this error:

screen shot 2016-08-24 at 02 50 25

Removing NSObject as superclass from Animal makes it work as expected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment