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

前端 未结 6 1461
野性不改
野性不改 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:23

    Sometimes it is simple and cleaner to use try? than do-catch, when you call something that throws, but decided not to handle any errors. If you leave call with try? as-is, compiler will warn you about unused result, which is not good. So you can discard results using _.

    Example:

    let _ = try? NSFileManager.defaultManager().moveItemAtURL(url1, toURL: url2)
    

提交回复
热议问题