Sneaky Swift Tricks: The fake Boolean

原文
gurad let 解包时候能很好的避免金字塔,但是如何知道哪里出错了呢


guard let keypath = dictionary["field"] as? String,
           let rule = dictionary["rule"] as? String, 
           let comparator = FormFieldDisplayRuleComparator(rawValue: rule),                        
          let value = dictionary["value"]
 else { return nil }

用where语句就行了

func diagnose(file: String = #file, line: Int = #line) -> Bool {
   print("Testing \(file):\(line)")
   return true
}

变成这样了

guard let keypath = dictionary["field"] as? String where diagnose(), 
     let rule = dictionary["rule"] as? String where diagnose(),
     let comparator = FormFieldDisplayRuleComparator(rawValue: rule) where diagnose(), 
    let value = dictionary["value"] where diagnose()
   else { return nil }

还有俩种方式

extension Optional {    @inline(__always) func expect(@autoclosure msg: () -> String) -> T {    
    guard let value = self else { fatalError(msg()) }   
     return value   
 }}

func diagnoseOptional(optional: T?, message: String =         "Found nil in \(#file) at line \(#line)") -> T? {
    guard let unwrapped = optional else {   
     print(message)   
     return nil 
 }  
return unwrapped
}

你可能感兴趣的:(Sneaky Swift Tricks: The fake Boolean)