Skip to content

Instantly share code, notes, and snippets.

@benaneesh
Created May 12, 2016 16:28
Show Gist options
  • Save benaneesh/143590a695dce3960a9d1c372edb4135 to your computer and use it in GitHub Desktop.
Save benaneesh/143590a695dce3960a9d1c372edb4135 to your computer and use it in GitHub Desktop.
public extension RangeReplaceableCollectionType where Index: Comparable {
public subscript (safe index: Index) -> Generator.Element? {
get {
guard indices ~= index else { return nil }
return self[index]
}
set {
guard indices ~= index else { return }
if let newValue = newValue {
self.removeAtIndex(index)
self.insert(newValue, atIndex: index)
}
}
}
public mutating func removeAtIndex(safe index: Self.Index) -> Self.Generator.Element? {
guard indices ~= index else { return nil}
return self.removeAtIndex(index)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment