尝试在枚举中采用StringLiteralConvertible时:
enum Component: StringLiteralConvertible {
case Static(String)
case AnyInt
typealias ExtendedGraphemeClusterLiteralType = String
typealias UnicodeScalarLiteralType = String
init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
}
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
}
init(stringLiteral value: String) {
}
}
我收到以下错误:
Variable 'self' used before initialized
在每个初始化器中。
根据NSHipster,符合该协议的正确方法涉及覆盖带有字符串文字的类func并返回所需类/结构的对象。像这样:
static func convertFromStringLiteral(value: String) -> CGPoint {
return NSPointFromString(value) // CGPointFromString on iOS
}
在最近的一次Swift更新中有没有改变?是否可以采用StringLiteralConvertible作为枚举?
答案 0 :(得分:5)
StringLiteralConvertible
协议已更改且convertFromStringLiteral
功能不再存在。
您已拥有所需的初始值设定项。错误是您没有为self
分配值。示例实现:
enum Component: StringLiteralConvertible {
case Static(String)
case AnyInt
init(stringLiteral value: String) {
self = Static(value)
}
init(extendedGraphemeClusterLiteral value: String) {
self = Static(value)
}
init(unicodeScalarLiteral value: String) {
self = Static(value)
}
}
let comp : Component = "Foo"
Swift 3/4更新:
enum Component: ExpressibleByStringLiteral {
case `static`(String)
case anyInt
init(stringLiteral value: String) {
self = .static(value)
}
}
let comp: Component = "Foo"