首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以在Swift中从枚举名称和值的rawValue在运行时实例化或生成枚举值吗?

问我可以在Swift中从枚举名称和值的rawValue在运行时实例化或生成枚举值吗?
EN

Stack Overflow用户
提问于 2020-05-12 20:22:42
回答 2查看 130关注 0票数 2

我们正在使用SWIFT5.0。我需要定期地将字符串列表转换成一组枚举案例。我轻松地编写了一个Kotlin函数,它在运行时接受一个枚举类和一个字符串列表,并将它转换为一个Java EnumSet (两个一起工作的函数):

代码语言:javascript
复制
fun <EnumT : Enum<EnumT>> ConvertStrToEnum(enumClass: Class<EnumT>, str: String?): EnumT? {
    if (str == null)
        return null
    for (enumval in enumClass.enumConstants) {
        if (enumval.toString() == str)
            return enumval
    }
    throw IllegalArgumentException("Gave an invalid enum value for class ${enumClass.canonicalName}: [$str]")
}

fun <EnumT : Enum<EnumT> > ConvertStrArrayToEnumSet(enumClass: Class<EnumT>, array: List<String>?) : EnumSet<EnumT> {
    val set = EnumSet.noneOf(enumClass)
    array?.forEach { value -> ignoreExceptions { set.add(ConvertStrToEnum(enumClass, value)) } }
    return set
}

而且,要明确的是,实际使用是:

代码语言:javascript
复制
var intent: EnumSet<Intent>
intent = ConvertStrArrayToEnumSet(Intent::class.java, filters.array(MatchFilter.Intent.jsonName))

我能否在Swift 5中编写一个实现相同结果的函数?我写这个是为了一次转换,下面是一个例子。如果我不能编写这个函数,我将在整个应用程序中重复这个样板代码。

代码语言:javascript
复制
  public var intents: Set<Intent>
  if let jsonIntents = filters?["intent"] as? Array<String> {
     for jsonIntent in jsonIntents {
        if let intent = Intent(rawValue: jsonIntent) {
           intents.insert(intent)
        }
     }
  }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-12 20:33:14

假设你的墓穴是RawRepresentable和RawValue == String..。

Swift中的Enum没有像Enum那样的特殊“基类”。但在这种情况下,我们确实需要利用它们的共同属性-- RawRepresentable和Hashable。当然,很多非公立学校也有这样的财产。因此,我们的方法不仅适用于枚举,而且适用于符合这两种协议的任何类型。太好了不是吗?

代码语言:javascript
复制
func convertStringArrayToEnumSet<T>(type: T.Type, _ strings: [String]) -> Set<T> 
    where T : RawRepresentable & Hashable, T.RawValue == String {
    Set(strings.compactMap(T.init(rawValue:)))
}

注意compactMap的使用,它丢弃任何无效的原始值。

实际上,您可以将其概括为不只是字符串数组,而是任何数组:

代码语言:javascript
复制
func convertRawValueArrayToEnumSet<T>(type: T.Type, _ rawValues: [T.RawValue]) -> Set<T> 
    where T : RawRepresentable & Hashable {
    Set(rawValues.compactMap(T.init(rawValue:)))
}
票数 1
EN

Stack Overflow用户

发布于 2020-05-12 23:09:43

清洗机的答案是好的,但我看到你在错误处理方面付出了一些努力。Swift不太适合帮助你,所以你必须自己做扩展。

(Dictionary和RawRepresentable来自Swift 1,没有错误。他们从来没有得到现代化,只是退赛。)

代码语言:javascript
复制
/// Acts as a dictionary that `throw`s instead of returning optionals.
public protocol valueForKeyThrowingAccessor {
  associatedtype Key

  /// Should just be a throwing subscript, but those don't exist yet.
  func value<Value>(for: Key) throws -> Value
}
代码语言:javascript
复制
/// Acts as a dictionary.
public protocol valueForKeySubscript: valueForKeyThrowingAccessor {
  associatedtype Value

  subscript(key: Key) -> Value? { get }
}

public extension valueForKeySubscript {
  /// - Throws: `KeyValuePairs<Key, Value>.AccessError.noValue`
  func value(for key: Key) throws -> Value {
    guard let value = self[key]
    else { throw KeyValuePairs<Key, Value>.AccessError.noValue(key: key) }

    return value
  }

  /// - Throws: `KeyValuePairs<Key, Value>.AccessError.typeCastFailure`
  func value<Value>(for key: Key) throws -> Value {
    guard let value = try value(for: key) as? Value
    else { throw KeyValuePairs<Key, Value>.AccessError.typeCastFailure(key: key) }

    return value
  }
}

extension Dictionary: valueForKeySubscript { }
代码语言:javascript
复制
public extension KeyValuePairs {
  /// An error throw from trying to access a value for a key.
  enum AccessError: Error {
    case noValue(key: Key)
    case typeCastFailure(key: Key)
  }
}
代码语言:javascript
复制
public extension RawRepresentable {
  /// Like `init(rawValue:)`, if it was throwing instead of failable.
  /// - Throws: `RawRepresentableExtensions<Self>.Error.invalidRawValue`
  /// if there is no value of the type that corresponds with the specified raw value.
  init(_ rawValue: RawValue) throws {
    guard let instance = Self(rawValue: rawValue)
    else { throw RawRepresentableExtensions<Self>.Error.invalidRawValue(rawValue) }

    self = instance
  }
}

/// A namespace for nested types within `RawRepresentable`.
public enum RawRepresentableExtensions<RawRepresentable: Swift.RawRepresentable> {
  public enum Error: Swift.Error {
    case invalidRawValue(RawRepresentable.RawValue)
  }
}

public extension InitializableWithElementSequence where Element: RawRepresentable {
  /// - Throws: `RawRepresentableExtensions<Element>.Error.invalidRawValue`
  init<RawValues: Sequence>(rawValues: RawValues) throws
  where RawValues.Element == Element.RawValue {
    self.init(
      try rawValues.map(Element.init)
    )
  }
}
代码语言:javascript
复制
/// A type that can be initialized with a `Sequence` of its `Element`s.
public protocol InitializableWithElementSequence: Sequence {
  init<Sequence: Swift.Sequence>(_: Sequence)
  where Sequence.Element == Element
}

extension Array: InitializableWithElementSequence { }
extension Set: InitializableWithElementSequence { }
代码语言:javascript
复制
extension InitializableWithElementSequence where Element == Intent {
  init(filters: [String: Any]) throws {
    try self.init(
      rawValues: try filters.value(for: "intent") as [String]
    )
  }
}
代码语言:javascript
复制
try filters.map(Set.init)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61761239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档