Does “let _ = …” (let underscore equal) have any use in Swift?

前端 未结 6 1466
野性不改
野性不改 2020-12-11 02:50

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

I\'ve seen question and answers for What's the _ underscore representative of in Swift References? a

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 03:26

    if let _ = something {
        ...
    }
    

    is equal to

    if something != nil {
        ...
    }
    

    If you replaced the underscore with a property name, the fix that Xcode would suggest is the second option (it would not suggest the first). And that's because the second option makes more programming sense. However—and this is something Apple themselves stress to developers—write the code that is the most readable. And I suspect the underscore option exists because in some cases it may read better than the other.

提交回复
热议问题