代码之家  ›  专栏  ›  技术社区  ›  Curt Rand

Swift iOS:如何重构if语句的许多条件?

  •  1
  • Curt Rand  · 技术社区  · 7 年前

       override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        var dictionary = [String : Any]()
    
        if let jsonData = A0SimpleKeychain().string(forKey:"Dictionary")?.data(using: .utf8), let jsonDictionary = try! JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as? [String : Any] {
            dictionary = jsonDictionary
        }
    
        if let key = dictionary["key"] as? String, !apiKey.isEmpty, let shouldSync = context as? Bool  {
          // Do Stuff
        } else {
         // Do Stuff
        }
       }
    

    但是,我觉得有更好的方法来实现这一点,特别是if语句检查。将来可能需要检索更多的字典值。如果有人有任何建议,我将不胜感激。

    编辑:我正在尽力不使用bang操作符。这就是为什么我要使用很多条件。

    1 回复  |  直到 7 年前
        1
  •  0
  •   JonJ    7 年前

    guard
        let jsonData = A0SimpleKeychain().string(forKey: "Dictionary")?.data(using: .utf8),
        let dictionary = try! JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as? [String : Any],
        let key = dictionary["key"] as? String,
        !apiKey.isEmpty,
        let shouldSync = context as? Bool 
    else {
        // Failed. Do stuff.
    }
    
    // Conditions all passed. Continue...
    

    当“test”失败时,guard语句将失败。