Skip to content

Instantly share code, notes, and snippets.

@harlanhaskins
Last active August 29, 2015 14:19
Show Gist options
  • Save harlanhaskins/76f7af8056656114ceb1 to your computer and use it in GitHub Desktop.
Save harlanhaskins/76f7af8056656114ceb1 to your computer and use it in GitHub Desktop.
SafeArray -- a safe Swifty Array abstraction
import Foundation
struct SafeArray<T> {
private var values: [T]
init(_ values: [T]) {
self.values = values
}
subscript(index: Int) -> T? {
if index >= 0 && values.count > index {
return values[index]
}
return nil
}
}
extension Array {
var safe: SafeArray<T> {
return SafeArray(self)
}
}
@harlanhaskins
Copy link
Author

Usage

let safeNumbers = [1,2,3,4].safe

if let fifth = safeNumbers[4] {
   println("I will never be called")
} else {
   println("I WILL be called")
}

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