3 ms·
This all looks good to me until I'm unwrapping an optional and checking it's length in Swift, which normally looks like: guard let array = obj.someArray,
by zapzupnz 8y ago
This all looks good to me until I'm unwrapping an optional and checking it's length in Swift, which normally looks like:
guard let array = obj.someArray,
array.count > 0 else {
throw SomeError
}
- pantalaimon 8y ago`array.count < 1` still sounds reasonable though.
- zapzupnz 8y agoOnly if I _want_ the array to be empty, otherwise I have to put an ! in front of the that — which in Swift also needs brackets — which is just adding noise to the signal, really, which really defeats the purpose of avoiding the greater than symbol here.
- saagarjha 8y agoA 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)
- zapzupnz 8y agoWell 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.
- saagarjha 8y agoIn 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.
- deathanatos 8y agoWhy can that not be swapped to: guard let array = obj.someArray, 0 < array.count else { throw SomeError } ?
- zapzupnz 8y agoIt could be changed to that, but what am I really asking? "Is zero lower than the length of my array" is a bizarre way to word the question, as opposed to "is the length of my array greater than zero". I believe in self-documenting and obvious code, and I think if statements should read as much like a human sentence as possible.