Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Created January 13, 2021 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturdysturge/5f2e14f547ce1f1d7a2b47ed8a76650b to your computer and use it in GitHub Desktop.
Save sturdysturge/5f2e14f547ce1f1d7a2b47ed8a76650b to your computer and use it in GitHub Desktop.
import Foundation
extension Array {
subscript(index: Index, default defaultValue: @autoclosure () -> Element) -> Element {
if indices.contains(index) {
//If the index is valid we have no problem returning the value
return self[index]
} else {
//Otherwise we return the default which can't be nil
return defaultValue()
}
}
subscript(index: Index, default defaultValue: @autoclosure () -> Element?) -> Element? {
if indices.contains(index) {
//If the index is valid we have no problem returning the value
return self[index]
} else {
//Otherwise we return the default which may be nil
return defaultValue()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment