Logo for tanaschita.com

Safe array subscription in Swift

An extension to access array elements with conditional binding

10 May 2020 · 2 min read

The possibility to use optionals in Swift allows us to write safe and expressive code. However, accessing elements from an array is not safe by default.

let shoppingList = ["apples", "raspberries"]
let item = shoppingList[2]

Accessing an element this way will crash the app if the element isn’t there. By adding the following extension to our code base, we have the possibility to access it in a safe way.

extension Collection {
/// Returns the element at the specified index if it exists, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}

We know can access the item with conditional binding:

if let item = shoppingList[safe: 2] {
// use item
}
Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swift

basics

Working with Strings in Swift

Learn how to use Swift's String type and its companions Character, Index and Substring.

05 Jun 2021 · 5 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum