jeudi 13 septembre 2018

Swift iOS: How to refactor a lot of conditions for if statement?

I have a string that is retrieved from a keychain, and I transform the string to a dictionary. Then, I check the values of the dictionary to see wether or not it is nil or empty.

   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
    }
   }

However, I feel like there is a better way to accomplish this specifically the if statement checks. There might be more dictionary values I have to retrieve in the future. If anyone has tips or suggestions, I will deeply appreciate it.

Edit: I am trying my best to not use the bang operator. That is why I am using a lot of conditions.

Aucun commentaire:

Enregistrer un commentaire