我有一个在Xcode11.3,Swift 5.1中运行良好的枚举。我刚刚升级到Xcode 11.4 Swift 5.2,现在我得到了一个重新声明错误:


我做了一个全局搜索,没有任何其他枚举具有相同的名称,也没有任何其他类或枚举使用该方法。在我升级之前它从来没有发生过。我做了一个干净的,深入的清理,并清除了派生的数据。
如何修复此错误?
enum ActivityType: String {
case north
case south
case east
case west
case up
case down
case still
static func value(from raw: String?) -> ActivityType {
switch raw {
case ActivityType.north.rawValue():
return .north
case ActivityType.south.rawValue():
return .south
case ActivityType.east.rawValue():
return .east
case ActivityType.west.rawValue():
return .west
case ActivityType.up.rawValue():
return .up
case ActivityType.down.rawValue():
return .down
case ActivityType.still.rawValue():
return .still
default:
return .still
}
}
func rawValue() -> String { // error occurs here
switch self {
case .north:
return "north"
case .south:
return "south"
case .east:
return "east"
case .west:
return "west"
case .up:
return "up"
case .down:
return "down"
case .still:
return "still"
}
}
}发布于 2020-05-05 07:36:47
由于您的enum已经将String作为原始值类型,因此您将拥有一个自动生成的rawValue属性。它与您的rawValue()函数冲突。但是,这是不必要的,因为您可以只使用自动生成的代码:
enum ActivityType: String {
case north, south, east, west, up, down, still
static func value(from rawValue: String?) -> ActivityType {
guard let rawValue = rawValue, let activityType = ActivityType(rawValue: rawValue) else {
return .still
}
return activityType
}
}上面的代码与您的代码执行相同的操作。当然,这在很大程度上也是不必要的,因为您可以直接使用ActivityType(rawValue: myString) ?? .still。
发布于 2020-05-05 09:10:39
protocol RawRepresentableWithDefault: RawRepresentable {
static var `default`: Self { get }
}
extension RawRepresentableWithDefault {
init(rawValue: RawValue?) {
self = rawValue.flatMap(Self.init) ?? .default
}
}enum ActivityType: String {
case north, south, east, west, up, down, still
}
extension ActivityType: RawRepresentableWithDefault {
static let `default` = still
}https://stackoverflow.com/questions/61603251
复制相似问题