Skip to content

Instantly share code, notes, and snippets.

@hyukhur
Last active October 23, 2017 02:55
Show Gist options
  • Save hyukhur/7e49d27afaaaddcd3b1aec2d276328a4 to your computer and use it in GitHub Desktop.
Save hyukhur/7e49d27afaaaddcd3b1aec2d276328a4 to your computer and use it in GitHub Desktop.
Safety Array subscript, And Safety Array for Optional Index
import Foundation
extension Array {
public subscript (safe index: Array.Index) -> Element? {
get {
return indices ~= index ? self[index] : nil
}
set {
guard let element = newValue else { return }
self[index] = element
}
}
}
extension Array {
subscript (safe index: Array.Index?) -> Element? {
get {
guard let index = index else { return nil }
return indices ~= index ? self[index] : nil
}
set {
guard let index = index else { return }
guard let element = newValue else { return }
if indices ~= index
self[index] = element
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment