Skip to content

Instantly share code, notes, and snippets.

@dnedrow
Created February 26, 2020 23:59
Show Gist options
  • Select an option

  • Save dnedrow/c44acf08db02595c4fd601ee9e94eb45 to your computer and use it in GitHub Desktop.

Select an option

Save dnedrow/c44acf08db02595c4fd601ee9e94eb45 to your computer and use it in GitHub Desktop.
This extension to Array provides safe access to any index in an array, with a clean non-crashy result.
//
// Array_SafeAccess.swift
//
// Created by Zhao, Tyler on 6/26/19.
//
import Foundation
/// This protocol describes a function designed to return an optional
/// on a bad array access.
public protocol SafeIndexAccessible {
// swiftlint:disable missing_docs
associatedtype Element
// swiftlint:enable missing_docs
/// Safe access to objects in an array. On a bad access, nil is returned.
/// Usage:
/// ```
/// let myArr = [Double](repeating: 2.0, count 3) // Creates an array of size 3.
/// let test = myArr[safe: 3] // test is nil, as there is no array element at index 3.
/// ```
subscript(safe index: Int) -> Element? { get }
}
extension Array: SafeIndexAccessible {
public subscript(safe index: Int) -> Element? {
guard indices.contains(index) else { return nil }
return self[index]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment