[arrays] How to return first 5 objects of Array in Swift?

SWIFT 4

A different solution:

An easy inline solution that wont crash if your array is too short

[0,1,2,3,4,5].enumerated().compactMap{ $0.offset < 3 ? $0.element : nil }

But works fine with this.

[0,1,2,3,4,5].enumerated().compactMap{ $0.offset < 1000 ? $0.element : nil }

Usually this would crash if you did this:

[0,1,2,3,4,5].prefix(upTo: 1000) // THIS CRASHES

[0,1,2,3,4,5].prefix(1000) // THIS DOESNT