Accessing indices safely
suggest changeThe following extension lets you access an array index without knowing whether that index is in bounds. The subscript returns nil when it is not.
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