Hacker News new | ask | show | jobs
by saagarjha 2752 days ago
A somewhat stupid way to solve this issue (of what is likely poorly-designed API, given what you're trying to do here; optional Arrays are generally a code smell) is to abuse the nil coalescing operator:

  guard !(obj.someArray?.isEmpty ?? true)
1 comments

Well sure, except if the array is optional (and I agree it's code smell, but that's what you get when you use other peoples' libraries, I guess) that statement doesn't unwrap the array for me to use; I'll either need to do it manually on a second line (waste of effort) or every time I try accessing that variable. If I access it a lot, this is inefficient duplication.

Plus, I don't like abusing the nil coalescing operator. Once you're abusing anything, you're adding signal to noise and making the intent of a statement less clear than necessarily, I feel.

+1 for isEmpty, though. According to the docs, count iterates over collections that don't conform to RandomAccessCollection, so best to avoid unnecessary overhead by adopting good practice! Thanks for that.

In your specific example, it didn't look like you wanted to use that array, so I thought I could save you a variable. If you are planning to use it, then by all means bind it to a variable for reuse.
What other use is there for a conditional let?
I thought your only use for the array was to check its count. Now that I think about it, that was probably a stupid assumption.