c# - 您如何声明类型为 'enum' 的参数(即它可以采用任何枚举)?

标签 c# swift enums arguments

在 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/

相关文章:

c# - C#中的面向对象问题

swift - 在 WatchOS 中使用列表时滚动行为不正确

css - 根据 View 的枚举属性显示的内容更改表行颜色。 ASP.Net MVC

c# - AspNet.Identit 2.1.0 ConfirmEmailAsync 总是返回无效的 token

c# - 如何将 WPF NotifyIcon 与 Caliburn.Micro 集成

c# - Linq 语句中的正则表达式?

ios - UICollectionView 未在屏幕上加载

ios - 如何将 Facebook 的 Buck Build 安装到现有的 Xcode 项目中?

c++ - 如何在 C++ 中进行从枚举到类型的转换(并在模板中使用)?

mysql - MySQL 如何存储枚举?