com.iavian
com.iavian

Reputation: 477

Optional in Swift, return count of array

Help me with Optional hell in Swift. How to return count of array for key "R". self.jsonObj can be null

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
  return (self.jsonObj["R"]! as? NSArray)?.count;
}

Upvotes: 2

Views: 5061

Answers (3)

Mike S
Mike S

Reputation: 42335

I'm guessing that you'll want to return 0 if there's nothing in the array. In that case, try the Nil Coalescing Operator:

return (self.jsonObj?["R"] as? NSArray)?.count ?? 0;

Edit: As @vacawama's answer points out, it should be self.jsonObj?["R"] instead of self.jsonObj["R"]! in case self.jsonObj is nil.

Upvotes: 2

vacawama
vacawama

Reputation: 154631

Let's take this a step at a time.

self.jsonObj may be nil so you need to treat it as an Optional:

self.jsonObj?["R"]

This will either return 1) nil if self.jsonObj is nil or if "R" is not a valid key or if the value associated with "R" is nil 2) an Optional wrapped object of some type. In other words, you have an Optional of some unknown type.

The next step is to find out if it is an NSArray:

(self.jsonObj?["R"] as? NSArray)

This will return an Optional of type NSArray? which could be nil for the above reasons or nil because the object in self.jsonObj was some other object type.

So now that you have an Optional NSArray, unwrap it if you can and call count:

(self.jsonObj?["R"] as? NSArray)?.count

This will call count if there is an NSArray or return nil for the above reasons. In other words, now you have an Int?

Finally you can use the nil coalescing operator to return the value or zero if you have nil at this point:

(self.jsonObj?["R"] as? NSArray)?.count ?? 0

Upvotes: 10

Bryan Chen
Bryan Chen

Reputation: 46598

assuming self.jsonObj is NSDictionary? or Dictionary<String, AnyObject>?

return self.jsonObj?["R"]?.count ?? 0

Upvotes: 0

Related Questions