Raw Value Types
The Swift doc says:
Raw values can be strings, characters, or any of the integer or floating-point number types.
However, this is not the complete set of types that can serve as enumeration raw values. The fact is raw values can be any ExpressibleBy*Literal & Equatable
types. For example:
extension CGSize: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = CGSizeFromString(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self = CGSizeFromString(value)
}
public init(unicodeScalarLiteral value: String) {
self = CGSizeFromString(value)
}
}
enum ScreenSize: CGSize {
case iPhone4 = "{320, 480}"
case iPhone5 = "{320, 568}"
case iPhone6 = "{375, 667}"
case iPhone6Plus = "{414, 736}"
}
Of course, you can also implement conformance to RawRepresentable
manually, but that's usually much more tedious for enums with more than 3 cases, as you can see below:
enum ScreenSize: RawRepresentable {
case iPhone4
case iPhone5
case iPhone6
case iPhone6Plus
init?(rawValue: CGSize) {
switch rawValue {
case CGSize(width: 320, height: 480):
self = .iPhone4
case CGSize(width: 320, height: 568):
self = .iPhone5
case CGSize(width: 375, height: 667):
self = .iPhone6
case CGSize(width: 414, height: 736):
self = .iPhone6Plus
default:
return nil
}
}
var rawValue: CGSize {
switch self {
case .iPhone4:
return CGSize(width: 320, height: 480)
case .iPhone5:
return CGSize(width: 320, height: 568)
case .iPhone6:
return CGSize(width: 375, height: 667)
case .iPhone6Plus:
return CGSize(width: 414, height: 736)
}
}
}