Search code examples
swiftif-statementoption-typeoptional-binding

Making a variable from if statement global


While encoding JSON, I´m unwrapping stuff with an if let statement, but I'd like to make a variable globally available

do {
  if
    let json = try JSONSerialization.jsonObject(with: data) as? [String: String], 
    let jsonIsExistant = json["isExistant"] 
  {
    // Here I would like to make jsonIsExistant globally available
  }

Is this even possible? If it isn't, I could make an if statement inside of this one, but I don't think that would be clever or even possible.


Solution

  • delclare jsonIsExistant at the place you want it. If you are making an iOS App, than above viewDidLoad() create the variable

    var jsonIsExistant: String?
    

    then at this point use it

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], 
        let tempJsonIsExistant = json["isExistant"] {
            jsonIsExistant = tempJsonIsExistant
        }
    }
    

    This could be rewritten like so though

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] { 
            jsonIsExistant = json["isExistant"]
        }
    } catch {
        //handle error
    }
    

    If handled the second way, then you have to check if jsonIsExistant is nil before use, or you could unwrap it immediately with a ! if you are sure it will always have a field "isExistant" every time that it succeeds at becoming json.