How do I tell which guard statement failed?

前端 未结 7 1655
醉梦人生
醉梦人生 2020-12-28 17:58

If I’ve got a bunch of chained guard let statements, how can I diagnose which condition failed, short of breaking apart my guard let into multiple statements?

Given

7条回答
  •  时光说笑
    2020-12-28 19:00

    Erica Sadun just wrote a good blog post on this exact topic.

    Her solution was to hi-jack the where clause and use it to keep track of which guard statements pass. Each successful guard condition using the diagnose method will print the file name and the line number to the console. The guard condition following the last diagnose print statement is the one that failed. The solution looked like this:

    func diagnose(file: String = #file, line: Int = #line) -> Bool {
        print("Testing \(file):\(line)")
        return true
    }
    
    // ...
    
    let dictionary: [String : AnyObject] = [
        "one" : "one"
        "two" : "two"
        "three" : 3
    ]
    
    guard
        // This line will print the file and line number
        let one = dictionary["one"] as? String where diagnose(),
        // This line will print the file and line number
        let two = dictionary["two"] as? String where diagnose(),
        // This line will NOT be printed. So it is the one that failed.
        let three = dictionary["three"] as? String where diagnose()
        else {
            // ...
    }
    

    Erica's write-up on this topic can be found here

提交回复
热议问题