我想在 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!")
}
}
}
}
我想我可以定义一个通用枚举类型 in the protocol但我没能让它发挥作用。
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 }
}
这将允许使用任何可哈希类型。
如果您要求类型只能是 RawRepresentable
,其中 RawValue
是 String
,您必须定义您的另一个协议(protocol)动物类型必须符合。
protocol AnimalType: Hashable, RawRepresentable {
var rawValue: String { get }
}
protocol AnimalStorageProtocol {
associatedtype Animal: AnimalType
var storage: [Animal: Int] { get set }
}
然后您只需设置枚举类型以符合 AnimalType
协议(protocol)。
enum CatType: String, AnimalType { ... }
enum DogType: String, AnimalType { ... }
关于swift - 在 Swift 中,如何在协议(protocol)扩展中使用通用枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44684576/