Why do I need underscores in swift?

Here it says, “Note: the _ means “I don’t care about that value””, but coming from JavaScript, I don’t understand what that means.

The only way I can get these functions to print was by using the underscores before the parameters:

func divmod(_ a: Int, _ b:Int) -> (Int, Int) {
    return (a / b, a % b)
}

print(divmod(7, 3))
print(divmod(5, 2))
print(divmod(12,4))

Without the underscores I have to write it like this to avoid any errors:

func divmod(a: Int, b:Int) -> (Int, Int) {
    return (a / b, a % b)
}

print(divmod(a: 7, b: 3))
print(divmod(a: 5, b: 2))
print(divmod(a: 12,b: 4))

I don’t understand this underscore usage. When, how and why do I use these underscores?

4 Answers
4

Leave a Comment