Skip to content

Instantly share code, notes, and snippets.

View LeeKahSeng's full-sized avatar

Lee Kah Seng LeeKahSeng

View GitHub Profile
struct AnyAnimal: Animal {
let name: String
private let walker: () -> Void
private let eater: (Any) -> Void
init<T: Animal>(_ animal: T) {
name = animal.name
walker = {
protocol Animal {
var name: String { get }
func walk()
associatedtype FoodType
func eat(food: FoodType)
}
class Cow: Animal {
// Create concrete type Animal
let myTiger = Tiger(withName: "My Tiger")
let myCow = Cow(withName: "My Cow")
// Instantiate AnyAnimal with concrete type Animal
let anyTiger = AnyAnimal.tiger(myTiger)
let anyCow = AnyAnimal.cow(myCow)
let animalArray: [AnyAnimal] = [anyTiger, anyCow]
let foodArray: [Any] = [Meat(), Grass()]
enum AnyAnimal: Animal {
case cow(Cow)
case tiger(Tiger)
var name: String {
switch self {
case let .cow(animal):
return animal.name
case let .tiger(animal):
let animalArray: [Animal] = [myTiger, myCow]
let foodArray: [Any] = [Meat(), Grass()]
for (animal, food) in zip(animalArray, foodArray) {
// Feed the animal with their favorite food
animal.eat(food: food)
}
protocol Animal {
var name: String { get }
func walk()
associatedtype FoodType
func eat(food: FoodType)
}
class Cow: Animal {
protocol Animal {
var name: String { get }
func walk()
}
class Cow: Animal {
let name: String
protocol Animal {
associatedtype FoodType
func eat(food: FoodType)
}
protocol Flyable {
/// Limit the speed of flyable
var speedLimit: Int { get }
func fly()
}
extension Flyable {
func fly() {
protocol Flyable {
// Make speedLimit only gettable
var speedLimit: Int { get }
func fly()
}
class Bird: Flyable {
// Make speedLimit private
private(set) var speedLimit = 20