Reputation: 19622
I have an enum that worked fine in Xcode 11.3, Swift 5.1. I just graded to Xcode 11.4 Swift 5.2 and now I get a redeclaration error:
I did a global search and there aren't any other enums with the same name nor any other classes or enums that use the method. It never occurred prior to my upgrade. I did a clean, deep clean, and cleared out derived data.
How can I fix this error?
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"
}
}
}
Upvotes: 0
Views: 313
Reputation:
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
}
Upvotes: 0
Reputation: 42149
Since your enum
already has String
as the raw value type, you have an autogenerated rawValue
property. It conflicts with your rawValue()
function. However, it is unnecessary, since you can just use the autogenerated code:
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
}
}
The above does the same as your code. Of course even that is largely unnecessary, since you could just use ActivityType(rawValue: myString) ?? .still
directly.
Upvotes: 3