Let's say we want to get the first element in type Optional U in a array of type [T], T may or may not be type casted into U what will you do?

  1. [T].first.flatmap{$0 as? U}

  2. [T].flatmap{$0 as? U}.first

Which would you choose?

The answer is, it depends.

They looked the same, but the performance behind them is totally different. First answer is a O(1) solution when the second is O(n). But the first answer is not always the right one. Like what I've just said, it depends.

If all of the element in [T] are definitely the same, so you can assume all elements in the array can either all can be casted into U or not, you should go with the first answer. Because you don't have to cast all the elements into another type before you fetch the first element and cast it.

What if the case is, T is a superclass of different concrete subclasses, and may be one of those subclasses or the protocol they conform to which happen to be U? the first answer can be wrong there since any elements in these array can have chance to be casted into U when the others not. So you should use the second approach.

Optimise performance is great, but when you're doing that, be aware of the reason of the original codes. The best answer of all cases is - keep your codes clean and comment them when necessary.

Subscribe to

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.