在 C# 中,您可以编写一个将任何枚举值作为参数的函数,方法是将参数声明为 Enum
类型,如下所示...
public enum FirstEnum
{
A,
B,
C
}
public enum SecondEnum
{
D,
E,
F
}
public void StoreValue(Enum key, object value)
{
myDictionary[key] = value; <-- Uses the enum as a key
}
StoreValue(FirstEnum.A, someItem); // Using the first enum type
StoreValue(SecondEnum.D, someItem); // Using the second enum type
StoreValue("Sam", someItem); // Won't compile since 'Sam' is not an enum
你能在 Swift 中做类似的事情吗?我知道您可以将参数 someEnum
声明为字符串并以这种方式使用它,但我正在尝试确定它是否可以像在 C# 中那样强制成为 Enum。
最佳答案
按照 Wain 的建议,你可以这样写:
enum FirstEnum: String
{
case
A,
B,
C
}
enum SecondEnum: String
{
case
D,
E,
F
}
//create a protocol
public protocol StringKeyEnum {
var rawValue: String {get}
}
//make the enumeration(s) conform to it
extension FirstEnum: StringKeyEnum {}
extension SecondEnum: StringKeyEnum {}
var myDictionary: [String: AnyObject] = [:]
//use it in your interface definitions
public func storeValue(key: StringKeyEnum, value: AnyObject)
{
myDictionary[key.rawValue] = value //<-- Uses the rawValue of enum as a key
}
let someItem = ""
storeValue(FirstEnum.A, value: someItem) // Using the first enum type
storeValue(SecondEnum.D, value: someItem) // Using the second enum type
storeValue("Sam", value: someItem) // Won't compile since 'Sam' is not a StringKeyEnum
关于c# - 您如何声明类型为 'enum' 的参数(即它可以采用任何枚举)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38750553/