Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional in Swift, return count of array

Tags:

swift

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;
}
like image 902
com.iavian Avatar asked Feb 12 '26 19:02

com.iavian


2 Answers

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

like image 173
vacawama Avatar answered Feb 15 '26 11:02

vacawama


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.

like image 29
Mike S Avatar answered Feb 15 '26 12:02

Mike S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!