我正在 Swift 中实现面向协议的方法,如下所示。这个概念看起来很有趣,但我希望你能明白。我的问题是如何为重复的打印任务实现通用功能。谢谢你的进步。
protocol Food {
var name: String { get }
}
struct Grass: Food {
var name: String { return "Grass" }
var calcium: Float!
}
struct Rice: Food {
var name: String { return "Rice" }
var calories: Float!
}
struct Insect: Food {
var name: String { return "Insect" }
var fiber: Float!
}
protocol Eat {
associatedtype food: Food
var name: String { get }
var itsFood: food { get }
}
struct Cow: Eat {
typealias food = Grass
var name: String { return "Cow" }
var itsFood: food {return food(calcium: 100)}
}
struct People: Eat {
typealias food = Rice
var name: String { return "People" }
var itsFood: food {return food(calories: 1000)}
}
struct Reptile: Eat {
typealias food = Insect
var name: String { return "Reptile" }
var itsFood: food {return food(fiber: 300)}
}
let cow = Cow()
print(cow.name)
print(cow.itsFood.name)
print(cow.itsFood.calcium)
let people = People()
print(people.name)
print(people.itsFood.name)
print(people.itsFood.calories)
let reptile = Reptile()
print(reptile.name)
print(reptile.itsFood.name)
print(reptile.itsFood.fiber)