user7024499
user7024499

Reputation: 961

Swift ExpressibleByIntegerLiteral - How exactly does it work?

Taken from iOs 10 Programming Fundamentals:

"Because Nest adopts ExpressibleByIntegerLiteral, we can pass an Int where a nest is expected, and our init(integerLiteral:) will be called AUTOMATICALLY....."

struct Nest : ExpressibleByIntegerLiteral {
     var eggCount : Int = 0
     init() {}
     init(integerLiteral val: Int) {
          self.eggCount = val
     }
}

Okay so my question is this...How does it get called automatically though?? My logic runs into a brick wall when I try to figure out why. From what I see, you can say:

var eggie : Nest = 5

but... okay where is the logic in how the number 5 after the equal sign is actually a shorthand for:

var eggie : Nest = Nest(5)

AKA the 'standard' way of initializing a new instance...

Is that just something hidden deep inside the ExpressibleByIntegerLiteral protocol that is handling that transformation?

Thanks

Upvotes: 4

Views: 1991

Answers (2)

Sweeper
Sweeper

Reputation: 271840

It's compiler magic, so unfortunately you cannot declare such a protocol yourself. :(

It has nothing to do with the internal workings of the ExpressibleByIntegerLiteral. The compiler only sees a variable of type Nest on the left and an integer literal on the right. It thinks,

Oh! The Nest type conforms to ExpressibleByIntegerLiteral! And I see an integer literal. This means that I can change the integer literal to Nest(integerLiteral: 5)!

It's as simple as that. This is also true for other ExpressibleByXXXLiteral protocols.

You cannot declare your own ExpressibleByMyClass protocol because the compiler doesn't know about it.

Upvotes: 8

Alexander
Alexander

Reputation: 63271

The ExpressibleBy*Literal protocols are Swift protocols to "hook" into special compiler behaviour. Without the compiler doing the lifting in the back, they wouldn't be able to do anything.

Upvotes: 3

Related Questions