Swift 如何使描述字符串的协议可表示枚举?

Swift 如何使描述字符串的协议可表示枚举?,swift,generics,enums,swift-protocols,rawrepresentable,Swift,Generics,Enums,Swift Protocols,Rawrepresentable,我有一个方法,它调用某个管理器的方法,用某个键保存int值。我的方法接收int和一些EnumKey枚举值作为键,挤出EnumKey的rawValue并将其作为字符串传递给管理器: set(value: Int, forKey key: EnumKey) { SomeManager.saveIntValueWithStringKey(valueToSave: value, keyToSave: key.rawValue) } enum EnumKey: String { cas

我有一个方法,它调用某个管理器的方法,用某个键保存int值。我的方法接收int和一些EnumKey枚举值作为键,挤出EnumKey的rawValue并将其作为字符串传递给管理器:

set(value: Int, forKey key: EnumKey) {
    SomeManager.saveIntValueWithStringKey(valueToSave: value, keyToSave: key.rawValue)
}

enum EnumKey: String { 
    case One="first key"
    case Two="second key"
}
我希望通过允许我的方法使用字符串原始值而不是EnumKey来接收每个枚举,使其更通用。在方法的实现中,我将密钥参数的类型从EnumKey替换为GenericKey协议,并使EnumKey符合此协议:

 set(value: Int, forKey key: GenericKey) {
    SomeManager.saveIntValueWithStringKey(valueToSave: value, keyToSave: key.rawValue)
}

protocol GenericKey {
    var rawValue: String { get }
}

enum EnumKey: String, GenericKey { 
    case One="first key"
    case Two="second key"
}
但是这个
字符串,GenericKey
看起来有点难看。我希望每个字符串可表示的枚举自动适应,而不提及它除了符合RawRepresentable和string原始类型之外,还符合GenericKey协议。比如:

protocol GenericKey: RawRepresentable {
    associatedtype RawValue = String
}
但编译器说“协议只能用作泛型约束,因为它具有自身或关联的类型要求”


有什么简单的方法可以解释编译器协议仅使用字符串类型的RawValue描述RawRepresentable对象?

您可以将函数定义为泛型,并将泛型类型定义为
RawRepresentable
,类型为
String
,如下所示:

class Test {
    func set<T: RawRepresentable>(value: Int, forKey key: T) where T.RawValue == String {
        print("value \(value), key: \(key.rawValue)")
    }
}

enum EnumKey: String {
    case One="first key"
    case Two="second key"
}

let t = Test()
t.set(value: 3, forKey: EnumKey.One) // prints "value 3, key: first key"
类测试{
func集(值:Int,forKey:T),其中T.RawValue==字符串{
打印(“value\(value),key:\(key.rawValue)”)
}
}
枚举枚举键:字符串{
案例一=“第一把钥匙”
案例二=“第二把钥匙”
}
设t=Test()
t、 set(值:3,forKey:EnumKey.One)//打印“值3,键:第一个键”