[swift-users] StringLiteralConvertible protocol question

Loïc Lecrenier loiclecrenier at icloud.com
Sun Jan 10 14:54:03 CST 2016


Hi :)

I have been trying to understand the StringLiteralConvertible protocol, but there is something that I still can’t explain.

//-----------------------------

extension Int : UnicodeScalarLiteralConvertible {
    public init(unicodeScalarLiteral value: UnicodeScalar) {
        self = 1
    }
}

extension Int : ExtendedGraphemeClusterLiteralConvertible {
    public init(extendedGraphemeClusterLiteral value: Character) {
        self = 2
    }
}

extension Int : StringLiteralConvertible {
    public init(stringLiteral value: String) {
        self = 3
    }
}

let a : Int = "\u{65}" // e
let b : Int = "\u{65}\u{0301}" // é
let c : Int = “hello"

//-----------------------------

If I only write the first extension: I can only initialize a, and its value will be 1.
If I write the first two extensions: I can initialize a and b, and their values will be 2. 
And if I keep the three extensions: a, b, and c will all have a value of 3.

So it seems like the compiler prefers calling the initializer from (in order of preference):
1. StringLiteralConvertible
2. ExtendedGraphemeClusterLiteralConvertible
3. UnicodeScalarLiteralConvertible

But for something to be StringLiteralConvertible, it needs to be ExtendedGraphemeClusterLiteralConvertible and UnicodeScalarLiteralConvertible, which means I have to define two initializers that will never be called.

Is that correct?
Is there a way to write something that is a unicode scalar literal, but not a string literal?

Thank you, 

Loïc








More information about the swift-users mailing list