Swift - Why String doesn't conform to RawRepresentable?

1.6k views Asked by At

I'm learning Swift and cannot realize why this code is correct:

enum Test1: String {
    case value
}

let test1 = Test1.value.rawValue

but this one is incorrect and shows me errors

struct MyStruct {
}

extension MyStruct: Equatable {
    static func == (lhs: MyStruct, rhs: MyStruct) -> Bool {
        return true
    }
}

enum Test2: MyStruct {
    case value
}

I browsed thru Swift.String sources and didn't find rawValue declaration. How does it work in Swift? Is String a built-in type that "automatically" conforms to RawRepresentable, but all other types have to explicitly declare its conformance?

2

There are 2 answers

0
AudioBubble On

Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration.

https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html


But that's only for using the colon-based shortcut syntax. It's no problem to manually conform.

enum Test2 {
  case value
}

extension Test2: RawRepresentable {
  init?(rawValue: MyStruct) {
    self = .value
  }
  
  var rawValue: MyStruct { .init() }
}
0
Alexander On

Notice that Test.value has type Test1, not String.

There is special treatment (implicit conformance to RawRepresentable), but it applies to string-valued enums, not String itself.