Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

ios - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...