Type Extension Example

How is the code below working? I’m confused by how the isMultiple() is able to access the int within catCount. Wouldn’t it need to have something like this.isMultiple() for it to work?

extension Int {
    var isEven: Bool {
        isMultiple(of: 2)
    }
}
 
let catCount = 3
print(catCount.isEven) // prints false

isMultiple() is a method of Int. So each Int intrinsically (no pun intended) has this method to call on.

4.isMultiple(of:2)
//true
7.isMultiple(of:2)
//false
25.isMultiple(of:5)
//true

I think that I’m more confused by how the isEven computed property is accessing isMultiple(). How does it know to access the instance of an Int that encompasses it without using self.isMultiple()? Is it because Swift is inferring that isMultiple() belongs to each instance and therefore doesn’t require a self. prefix?

Correct, it is missing self, making this an implicit definition. I don’t know how kosher that is in the world of swift, honestly. Python forces this to be explicit, whereas C++ you could can use implicit definitions if the situation allows it (although I don’t know if this is frowned upon).

More on this type of discussion: Revisiting requiring explicit `self.` when passing a method as an escaping closure - #13 by nonsensery - Pitches - Swift Forums

1 Like