Created
August 15, 2017 03:46
-
-
Save LeeKahSeng/d412c800cad8aeb006780011d39cc2b3 to your computer and use it in GitHub Desktop.
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
protocol Animal { | |
var name: String { get } | |
func walk() | |
associatedtype FoodType | |
func eat(food: FoodType) | |
} | |
class Cow: Animal { | |
let name: String | |
init(withName name: String) { | |
self.name = name | |
} | |
func walk() { | |
print("\(name) is walking in the farm.") | |
} | |
// Cow should eat grass | |
func eat(food: Grass) { | |
print("\(name) eat \(food.foodName)") | |
} | |
} | |
class Tiger: Animal { | |
let name: String | |
init(withName name: String) { | |
self.name = name | |
} | |
func walk() { | |
print("\(name) is walking in the jungle.") | |
} | |
// Tiger should eat meat | |
func eat(food: Meat) { | |
print("\(name) eat \(food.foodName)") | |
} | |
} | |
// Food for cow | |
struct Grass { | |
let foodName = "Grass" | |
} | |
// Food for tiger | |
struct Meat { | |
let foodName = "Meat" | |
} | |
// Create concrete of Animal | |
let myTiger = Tiger(withName: "My Tiger") | |
let myCow = Cow(withName: "My Cow") | |
let animalArray: [Animal] = [myTiger, myCow] // error: Protocol 'Animal' can only be used as a generic constraint because it has Self or associated type requirements |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment