Accessing indices safely
suggest changeBy adding the following extension to array indices can be accessed without knowing if the index is inside bounds.
extension Array {
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
example:
if let thirdValue = array[safe: 2] {
print(thirdValue)
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents