8

I'm trying to call the max function: max(x: T, y: T). However I keep getting the following error when I type max(2,3):

error: cannot call value of non-function type Int var a = max(2, 3)

I am a beginner, and I have never encountered a function signature that uses a type "T". SO threads relating to using the max function call it in the manner I am (like max(2,3) ) so I am not sure where I am going wrong.

I am looking for an explanation on the "T" and how to call functions that support generic types and how to make the max function return 3 when comparing integers 2 and 3.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Govind Rai
  • 14,406
  • 9
  • 72
  • 83
  • 1
    http://stackoverflow.com/a/33938397/2757916 a SO answer showing min/max usage like `max(2,3)` – Govind Rai Aug 06 '16 at 21:12
  • 3
    Sounds like you have defined a variable named `max`, causing a naming conflict with the function `max`. Although without seeing your code, it's hard to say. – Hamish Aug 06 '16 at 21:12
  • OMG... wth... you are absolutely correct. I finally understand what the error message is telling me... – Govind Rai Aug 06 '16 at 21:15
  • @Hamish Please post your comment as an answer so this question can be closed – Alexander Aug 09 '16 at 15:45
  • 1
    @AlexanderMomchliov Hmm... at the time, I voted to close this question as a "simple typographical error" due to the fact that it was lacking an MCVE & appropriate title for the actual problem (this has nothing to do with generics), therefore I doubted it would be of much use to any future searchers. However, if it isn't going to get closed, I agree that posting an answer (& editing the title) would be the best thing to do – I have gone ahead and done this. – Hamish Aug 09 '16 at 16:33
  • 2
    @Hamish It definitely is such a case, but to be honest, it seems like this would be a fairly common mistake. `min` and `max` are common variable names. I can imagine this happening to others. – Alexander Aug 09 '16 at 16:43

2 Answers2

16

The problem (as you've confirmed in the comments) is that you have defined a variable named max, causing a naming conflict with the function max(_:_:).

The solution therefore is to either specify the Swift module namespace (as George suggested) in order to disambiguate the fact that you're referring to the max(_:_:) function:

Swift.max(2, 3)

Or, preferably, you should consider renaming your variable. I strongly suspect that there's a more descriptive name you could give it (remember, the Swift API Design Guidelines favours clarity over brevity).

Community
  • 1
  • 1
Hamish
  • 78,605
  • 19
  • 187
  • 280
2

Are you calling max within extension Int?

Try Swift.max(2, 3).

George
  • 658
  • 5
  • 12
  • Hi George, as explained by Hamish in the comments above, I had a predefined variable named max which was causing a conflict. Thanks for your help. – Govind Rai Aug 06 '16 at 21:19