I tried to implement ExpressibleByIntegerLiteral
to my code and it has been terrible.
At last, it asked me to implement this init
// Cannot find type 'Builtin' in scope
init(_builtinIntegerLiteral value: Builtin.IntLiteral) {
}
The ExpressibleByIntegerLiteral
protocol has an associated type, IntegerLiteralType
, that you must define to be one of the standard integer literal types. You can do this explicitly but most folks do it implicitly, by supplying that type in their init(integerLiteral:)
definition. For example:
struct CDTrack {
var value: Int16
}
extension CDTrack: ExpressibleByIntegerLiteral {
init(integerLiteral value: Int16) {
self.value = value
}
}
let trackA: CDTrack = 32767
Here the parameter to init(integerLiteral:)
is Int16
, and that becomes the IntegerLiteralType
associated type. Now the compiler is able to check that the integer literal is in bounds. For example, this code fails to compile:
let trackB: CDTrack = 32768
^ Integer literal '32768' overflows when stored into 'CDTrack'
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"