cheesydoritosandkale cheesydoritosandkale - 4 years ago 127
Swift Question

Is there a difference between == true and != false in swift?

I had this code in my Swift App

func parseJSON() {

let urlString = ""

if NSURL(string: urlString) == true {
let url = NSURL(string: urlString)
let data = try? NSData(contentsOfURL: url!, options: []) as NSData
let json = NSData(data: data!)

// more code

However, even though the link actually worked and was true, the if statement was never met and it kept skipping it and moving to else. So I changed the code to

if NSURL(string: urlString) != false

and it worked perfectly. I'm not sure why though?

Answer Source

You don't really want to check for a boolean value when creating a NSURL, but rather make sure the NSURL you create is non-nil. Try wrapping it it in an if let statement like so to make sure whatever URL's you create are non-nil before executing further code.

   let urlString = ""

    if let url = NSURL(string: urlString) {
       if let data = try? NSData(contentsOfURL: url, options: []) {
           let json = NSData(data: data)
       } else { 
          //Handle case where data is nil
    } else { 
        //Handle case where url is nil 

Using if let statements in this way makes sure that the NSURL and NSData objects you are creating are non-nil and valid objects and then you can add an else statement to them to handle cases where your url or data objects are nil. This will save you from unwanted crashes due to force unwrapping with the ! operator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download