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

前端 未结 6 1453
野性不改
野性不改 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)
    
    0 讨论(0)
  • 2020-12-11 03:26

    Also, let _ = or _ = can be used when right side of expression is lazy variable and you want it calculated right now, but have no use for the value of this variable yet.

    A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

    Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete. Lazy properties are also useful when the initial value for a property requires complex or computationally expensive setup that should not be performed unless or until it is needed.


    Example:

    final class Example {
        private func deepThink() -> Int {
            // 7.5 million years of thinking
            return 42
        }
    
        private(set) lazy var answerToTheUltimateQuestionOfLifeTheUniverseAndEverything: Int = deepThink()
    
        func prepareTheAnswer() {
            _ = answerToTheUltimateQuestionOfLifeTheUniverseAndEverything
        }
    
        func findTheQuestion() -> (() -> Int) {
            // 10 millions of thinking
            let theQuestion = {
                // something
                return self.answerToTheUltimateQuestionOfLifeTheUniverseAndEverything
            }
    
            return theQuestion
        }
    }
    
    let example = Example()
    // And you *want* to get the answer calculated first, but have no use for it until you get the question
    example.prepareTheAnswer()
    
    let question = example.findTheQuestion()
    question()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 03:34

    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.

    0 讨论(0)
  • 2020-12-11 03:39

    You can user also @discardableResult in your own functions if sometimes you don't need the result.

    @discardableResult    
    func someFunction() -> String {
    
    }
    
    someFunction() // Xcode will not complain in this case
    
    0 讨论(0)
  • 2020-12-11 03:43

    Using let _ = ... specifically tells the compiler that you know that the expression on the right returns a value but that you don't care about it.

    In instances where the method has been marked with warn_unused_result, if you don't use the underscore then the compiler will complain with a warning. (Because in some cases it could be an error to not use the return value.)

    0 讨论(0)
提交回复
热议问题