Home > Mobile >  Swift - Why String doesn't conform to RawRepresentable?
Swift - Why String doesn't conform to RawRepresentable?

Time:11-26

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?

CodePudding user response:

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.

CodePudding user response:

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() }
}
  • Related