[英]Swift - Why String doesn't conform to RawRepresentable?
I'm learning Swift and cannot realize why this code is correct:我正在学习 Swift 并且无法理解为什么这段代码是正确的:
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.我浏览
Swift.String
来源,但没有找到rawValue
声明。 How does it work in Swift?它在 Swift 中如何工作? Is
String
a built-in type that "automatically" conforms to RawRepresentable
, but all other types have to explicitly declare its conformance? String
是“自动”符合RawRepresentable
的内置类型,但所有其他类型都必须显式声明其符合性吗?
Notice that value
has type Test1
, not String
.请注意,
value
的类型为Test1
,而不是String
。
There is special treatment (implicit conformance to RawRepresentable
), but it applies to string-valued enums, not String
itself.有特殊处理(隐式符合
RawRepresentable
),但它适用于字符串值枚举,而不是String
本身。
Raw values can be strings, characters, or any of the integer or floating-point number types.
原始值可以是字符串、字符或任何 integer 或浮点数类型。 Each raw value must be unique within its enumeration declaration.
每个原始值在其枚举声明中必须是唯一的。
https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html 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() }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.