Suragch Suragch - 7 months ago 58
Swift Question

Does "let _ = ..." (let underscore equal) have any use in Swift?

Does using

let _ = ...
have any purpose at all?

I've seen question and answers for What's the _ underscore representative of in Swift References? and I know that the underscore can be used to represent a variable that isn't needed.

This would make sense if I only needed one value of a tuple as in the example from the above link:

let (result, _) = someFunctionThatReturnsATuple()


However, I recently came across this code:

do {
let _ = try DB.run( table.create(ifNotExists: true) {t in
t.column(teamId, primaryKey: true)
t.column(city)
t.column(nickName)
t.column(abbreviation)
})

} catch _ {
// Error throw if table already exists
}


I don't get any compiler warnings or errors if I just remove the
let _ =
. It seems to me like this is simpler and more readable.

try DB.run( table.create(ifNotExists: true) {t in
t.column(teamId, primaryKey: true)
t.column(city)
t.column(nickName)
t.column(abbreviation)
})


The author of the code has written a book and a blog about Swift. I know that authors aren't infallible, but it made me wonder if there is something I am missing.

Answer

You will get a compiler warning if the method has been marked with a warn_unused_result from the developer documentation:

Apply this attribute to a method or function declaration to have the compiler emit a warning when the method or function is called without using its result.

You can use this attribute to provide a warning message about incorrect usage of a nonmutating method that has a mutating counterpart.