Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 787
user7024499 Avatar asked Dec 19 '22 11:12

user7024499


1 Answers

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.

like image 133
Sweeper Avatar answered Jan 14 '23 08:01

Sweeper