Search code examples
jsonxcodeswiftguard

Unwrap with guard statement from json to AnyObject


I need to parse data from dictionaries (containing the same keys) in a json file. The problem is that in some dictionaries the value for the same key is a string, but it is a float in the other. (Optional read: the reason for this is that the csv to json converter I use does recognise a negative decimal number as a string because there's a blank space after the dash: "- 4.50". I will delete that space and cast to float once the string is unwrapped.)

I tried to do the following:

guard let profit = data["profit"] as? AnyObject else { return }
if profit as! Float != nil {
  // Use this value
} else {
  // It is a string, so delete the space and cast to float
}

There must be an easy fix for this but no matter how I put the ? and ! in the guard statement, the compiler will complain.


Solution

  • The default type of a dictionary value is AnyObject anyway, so this type casting is redundant.

    You can check the type simply with the is operand

    guard let profit = data["profit"] else { return }
    if profit is Float {
      // Use this value
    } else {
      // It is a string, so delete the space and cast to float
    }
    

    Or including proper type casting

    guard let profit = data["profit"] else { return }
    if let profitFloat = profit as? Float {
      // Use this value
    } else if let profitString = profit as? String {
      // It is a string, so delete the space and cast to float
    }