Created
August 7, 2015 14:47
-
-
Save an0/eff2b9b31b07004b3dbd to your computer and use it in GitHub Desktop.
Generic Types are Not That Worse than Protocols
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Response to http://www.russbishop.net/swift-associated-types: | |
// 1. Type parameter leaking is a real problem(the `S` parameter of `buyFoodAndFeed` below can not be omitted — "We have no way to express that we don't care about the Supplement type parameter") but not as severe as is described in the article because non-generic subclasses of generic superclasses do not need type parameter re-specification when being used. | |
// 2. It is not true that "we have no way to link the type of F to Food". We can link Animal.F to Store.G. See `buyFoodAndFeed` below. | |
class Food { | |
required init() { | |
} | |
} | |
class Grass: Food { | |
} | |
class Supplement { | |
} | |
class Salt: Supplement { | |
} | |
class Animal<F: Food, S: Supplement> { | |
func feed(f: F) { | |
print("Yummy!") | |
} | |
func supplement(s: S) { | |
} | |
} | |
class Cow: Animal<Grass, Salt> { | |
override func feed(grass: Grass) { | |
print("Moo!") | |
} | |
} | |
class Holstein: Cow { | |
override func feed(grass: Grass) { | |
print("Hoo!") | |
} | |
} | |
class Store<G> { | |
} | |
func buyFoodAndFeed<F, S>(animal: Animal<F, S>, store: Store<F>) { | |
animal.feed(F()) | |
} | |
buyFoodAndFeed(Cow(), store: Store<Grass>()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment