Skip to content

Instantly share code, notes, and snippets.

@jimmya
Created October 23, 2019 19:36
Show Gist options
  • Save jimmya/33bc78f3c849040cb349a927caf8507c to your computer and use it in GitHub Desktop.
Save jimmya/33bc78f3c849040cb349a927caf8507c to your computer and use it in GitHub Desktop.
Array+Extension
import Foundation
public extension Array {
subscript (safe index: Int) -> Element? {
get {
return index < count && index >= 0 ? self[index] : nil
}
set {
if let element = newValue, index < count, index >= 0 {
self[index] = element
}
}
}
}
@RoBo-Inc
Copy link

RoBo-Inc commented Sep 9, 2020

"0..<count ~= index" is shorter than "index < count && index >= 0"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment