Last active
August 29, 2015 14:02
-
-
Save davidahouse/3269f60fe9a9d17649ce to your computer and use it in GitHub Desktop.
Playing around with Swift and subscripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension Array { | |
subscript(index:Int,defaultValue def:T) -> T { | |
if ( (0 <= index) && (index < self.count) ) { | |
return self[index] | |
} | |
else { | |
return def | |
} | |
} | |
} | |
var arr = ["one","two","three"] | |
let s = arr[4, defaultValue:"test"] | |
let t = arr[1, defaultValue:"test"] | |
And here's a variation of that last that uses T! so that you can just check if result == nil
rather than doing the Optional stuff
import UIKit
extension Array {
subscript(index:Int, defaultValue def:T!) -> T! {
if ( (0 <= index) && (index < self.count) ) {
return self[index]
}
else {
return def
}
}
}
var arr = ["one","two","three"]
let s = arr[4, defaultValue:"test"]
let t = arr[1, defaultValue:"test"]
let u = arr[10, defaultValue:nil]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a tweak that will allow return of Optional nil for invalid indexes, if that's desirable: