我想在它们之间共享功能CatZoo
,DogZoo
因为它们在后台存储相似的数据,但我也希望他们知道它们是什么,以便它们可以对特定数据进行操作,如DogZoo.makeNoise()
方法所示。
正确的类型是AnimalStorageProtocol.storage
什么?
enum CatType: String {
case lion
case tiger
case panther
}
enum DogType: String {
case coyote
case domestic
case wolf
}
struct CatZoo: AnimalStorageProtocol {
private var storage: [CatType: Int] // it's a bonus if they can stay private
}
struct DogZoo: AnimalStorageProtocol {
private var storage: [DogType: Int]
func makeNoise() {
for (key, value) in storage {
switch key {
case .coyote:
print("\(value) yips!")
case .domestic:
print("\(value) barks!")
case .wolf:
print("\(value) howls!")
}
}
}
}
protocol AnimalStorageProtocol {
// var storage: <RawRepresentable where RawRepresentable.RawValue == String: Int> { get set }
var storage: [RawRepresentable: Int] { get set }
}
extension AnimalStorageProtocol {
var isEmpty: Bool {
get {
for (_, value) in storage {
if value != 0 {
return false
}
}
return true
}
}
}
您可以根据需要使用两种不同的方法。
如果您不需要将类型设为枚举,则只需执行
protocol AnimalStorageProtocol {
associatedtype AnimalType: Hashable
var storage: [AnimalType: Int] { get set }
}
这将允许使用任何可哈希类型。
如果您要求类型只能位于aRawRepresentable
所在的位置,RawValue
则String
必须定义动物类型必须符合的另一种协议。
protocol AnimalType: Hashable, RawRepresentable {
var rawValue: String { get }
}
protocol AnimalStorageProtocol {
associatedtype Animal: AnimalType
var storage: [Animal: Int] { get set }
}
然后,您只需要设置您的枚举类型以符合AnimalType
协议即可。
enum CatType: String, AnimalType { ... }
enum DogType: String, AnimalType { ... }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句