Be careful about getting elements from an array
You have to remember that in Swift, if you try to access an index that is out of bounds, you will get a runtime error (EXC_BAD_INSTRUCTION) and the application will crash.
Currently, Swift Array type doesn’t have a safe method to access an element. Fortunately, we can add the appropriate extension ourselves, with a method that will return nil in the absence of an element with the given index, thanks to which you will be able to handle your flow by e.g. ‘guard’.
Here is the solution:
extension Collection { /// Returns the element at the specified index if it is within bounds, otherwise nil. subscript (safe index: Index) -> Element? { return 0 <= index && index < count ? self[index] : nil } }
In summary, the advantages of this solution are: type safety and O(1) performance.