Reputation: 101
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
}
When I using this code, there is a warning.
Initialization of immutable value 'cell' was never used; consider replacing with assignment to '_' or removing it
I know I have never used the cell, but I want to ask the question is "assignment to '_'", assignment to '-' is for what? I'm not familiar with Swift.
Upvotes: 1
Views: 1532
Reputation: 270980
So you wanted to know why Swift suggested you to replace cell
with _
?
In Swift, you can do pattern matching in assignment statements, for example:
let (x, y) = (1, 2)
The (x, y)
part is a tuple pattern. It creates two variables x
and y
. x
will have the value of 1
and y
the value of 2
. See how the variables and values match each other?
The _
is also a pattern, known as the Wildcard Pattern. By writing _
, you are basically saying "discard the value". So:
let _ = tableView.cellForRow(at: indexPath)
means that no variables will be created, but tableView.cellForRow(at: indexPath)
will still be evaluated. The method will be called.
Swift is suggesting you this because it sees that cell
is not used, it thinks that you might just want the side effects of cellForRow(at:)
. Therefore, it suggests that "why create a new variable just for the side effects? You probably don't need the return value anyway, replace it with a wildcard pattern!".
Upvotes: 0
Reputation: 9675
The warning means exactly what it says. You have initialized the constant "cell", but have not done anything with it. Therefore, you will get the warning until you use it somewhere else. This is part of how Xcode tracks variables.
The reason the compiler suggested "_" is simply because oftentimes you will want to make sure some reference is not nil. In those situations you can determine if something is nil by the code:
if let _ = someConstantThatMayBeNil {...}
and then you can use "someConstantThatMayBeNil" within the brackets and be certain it is not nil. If it was nil, and you didn't check, your program would crash.
I would recommend using Apple's App Development With Swift to gain a good foundation on its use.
Upvotes: 2