StringLiteralConvertible

StringLiteralConvertible

尝试在像这样的枚举中采用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作为枚举?

最佳答案

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"

10-08 16:56