ios - How to switch on a RawRepresentable enum type in Swift
问题描述
I have a method that takes type AnyObject and does some magic on it to turn it into a string. However, I cannot get a Swift enum type to work:
public func magic(on value: AnyObject) {
var stringVal: String
switch val {
case let val as Int:
stringVal = String(val)
case let val as RawRepresentable:
stringVal = val.rawValue
default:
assertionFailure("Unhandled type: \(type(of: val))")
stringVal = val.description
}
The compiler complains loudly:
- Protocol 'RawRepresentable' can only be used as a generic constraint because it has Self or associated type requirements
- Member 'rawValue' cannot be used on value of protocol type 'RawRepresentable'; use a generic constraint instead
I cannot figure out the necessary generic constraint syntax to make the compiler happy.
I also tried this:
case let val as RawRepresentable where RawValue == String:
stringVal = val.rawValue
But the compiler complains that RawValue can't be found in scope, even though it is an associatedtype for RawRepresentable.
解决方案
public func magic<T: AnyObject>(on value: T) where T: RawRepresentable, T: CustomStringConvertible {
var stringVal: String
switch value {
case let val as Int:
stringVal = String(val)
case let val where val.rawValue is String:
stringVal = val.rawValue as! String
case let val where val.rawValue is Int: // probaly check Int raw values as well
stringVal = String(val.rawValue as! Int)
default:
assertionFailure("Unhandled type: \(type(of: value))")
stringVal = value.description
}
print(stringVal)
}
推荐阅读
- java - Setters 和 getters 提示我“Java 找不到符号错误”,这使代码无法通过我的学习平台的测试
- angular - 如何全局模拟 Jasmine 的 Angular 服务
- spring-boot - @ExceptionHandler 捕获的异常不会被 MetricsWebFilter 记录
- mysql - 通过集群重启使用 Persistent Volume 持久化 MySQL pod 的数据
- c# - 如何将数据从 Windows 发送到 HID 键盘?
- node.js - 如何在 Tizen 设备上安装 NodeJS?
- java - 没有从 join() 方法中得到 InterruptedException
- reactjs - 如何解决 JSX 中的 if/else 语句?
- android - Flutter NetworkImage 无法从 url 加载 HEIC 图像
- python - 如何仅在需要时使用 anaconda python(在 linux 中)