How do I tell which guard statement failed?

前端 未结 7 1657
醉梦人生
醉梦人生 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:01

    My two cents:
    Since Swift doesn't let me add the where in the guard let, I came up with this solution instead:

    func validate<T>(_ input: T?, file: String = #file, line: Int = #line) -> T? {
        guard let input = input else {
            print("Nil argument at \(file), line: \(line)")
            return nil
        }
        return input
    }
    
    
    class Model {
        let id: Int
        let name: String
        
        init?(id: Int?, name: String?) {
            guard let id = validate(id),
                let name = validate(name) else {
                return nil
            }
            self.id = id
            self.name = name
        }
    }
    
    let t = Model(id: 0, name: "ok") // Not nil
    let t2 = Model(id: 0, name: nil) // Nil
    let t3 = Model(id: nil, name: "ok") // Nil
    
    0 讨论(0)
提交回复
热议问题