Govind Rai Govind Rai - 4 months ago 9
Swift Question

Unused variables and '_'

I am learning swift using learnxinyminutes.com

I'm having a hard time understanding a component of on of the examples on the site (below), namely the use of underscore in the

let
statements instead of variable names.

// Variadic Args
func setup(numbers: Int...) {
let _ = numbers[0]
let _ = numbers.count
}


I understand that swift wants you to use underscore if you never declare the variable, but 1) why would you want to declare variables you never use? And 2) is there a way to get those values out if you used
_
. And, 3) if so, how?

Answer

1) why would you want to declare variables you never use?

Generally you don't! There are some cases though where you might want to, such as the example Danny Buonocore gave. Another example might be this: say you want to check that a variable is non-nil before you do something, though you do not need that variable for the subsequent code. (A guard statement is probably more useful in these situations).

if let _ = titleString {
// Do something that doesn't use titleString, but where it being non-nil means this operation is valid
}

Another example is with Swift functions. Names for a second, third, etc. parameter must be identified whenever calling a function. For example:

func externalizedParameters(first: Int?, second: Int?) {
...
}

Which is called using externalizedParameters(5, second: 6).

But if you are doing something trivial, and the function name already makes it clear what the two parameters are, such as with a swap operation, you might not want to force the caller to explicitly state the name of the second parameter. In that case, you can use '_' because you don't care about the name of that externalized parameter:

func swap(first: Int?, _ second: Int?) {
    ...
}

This can then be called as swap(5, 6) as opposed to swap(5, second: 6).

2) is there a way to get those values out if you used _. & 3) if so, how?

No. You need to name the variable if you want to use the value.

Comments