Class have a variable name same as function name

  • A+
Category:Languages

I have the following class in Swift 4:

class AClass {     var add: (Int) -> Int {         return {             num in             return num + 1         }     }      func add(_ num: Int) -> Int {         return num + 20     } } 

Note that the variable and function have the same name 'add'.

Now in some other place I have this code:

let a = AClass() print(a.add(1)) 

I have run this code, and the result is 2 (which means the variable's block is called).

So here are the questions:

  1. Does the compiler always get the variable rather than call the function?

  2. Is there any way to call the function?

 


In Swift, instance methods are curried functions. Which means your add method is actually

static func add(_ self: AClass) -> (Int) -> Int 

This is why the property gets chosen over the function. Calling AClass.add(a)(1) yelds the expected result, the function gets called.

Now, why does the compiler allows this name clashing if the first place? I'm not sure, but I assume it has to do with the fully qualified name of those two entities. The property is simply add, while the function is add(_:).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: