Unused variables and '_'

I learn fast using learnxinyminutes.com

It is difficult for me to understand the component in the examples on the site (below), namely the use of underscore in operators letinstead of variable names.

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

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

+4
source share
3 answers

1) why do you want to declare variables that you never use?

, ! , , , , . : , , , - , . ( .

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

- Swift. , .. . :

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

externalizedParameters(5, second: 6).

- , , , , , . "_", :

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

swap(5, 6), swap(5, second: 6).

2) , _. 3) , ?

. , .

+2

, .

for _ in 0..<10 {

}

. , :

func myFunction(param1:String, param2:String) {

}

myFunction(param2: "second value", param1: "first value");

, :

func myFunction(param1:String, _ param2:String) {

}

, param2 , , .

+1

If you need to use a value inside a variable, declare it with a name, not _. The underline emphasizes: I know that this call returns a value, but we will not use it, so it does not need a name. Swift gives warnings about unused results of a function call, so this is a way to suppress this warning.

0
source

Source: https://habr.com/ru/post/1649580/


All Articles