User1932 User1932 - 5 months ago 11
Swift Question

Function with Swift

I am very new to Swift, actually I started learning it today. Can someone tell me whats wrong with calling the function in this way?

func myAddition(i:NSInteger,j:NSInteger) ->NSInteger {
i
j
return i+j
}

myAddition(5, 6)


Edit
I fixed the error by inserting j:

myAddition(5, j: 6)


is this normal? I am following a tutorial and there its working without j

Answer

If you want to be able to call the function without specifying the parameter names, then you have to tell Swift that there are no external parameter names for the function by using the underbar (_) as the external parameter name:

func myAddition(_ i:NSInteger, _ j:NSInteger) -> NSInteger {
    return i+j
}

myAddition(5, 6)

Do you really need an NSInteger as opposed to a normal Swift Int:

func myAddition(_ i:Int , _ j:Int) -> Int {
    return i+j
}

myAddition(5, 6)