Skip to content

Instantly share code, notes, and snippets.

@davidahouse
Last active August 29, 2015 14:02
Show Gist options
  • Save davidahouse/3269f60fe9a9d17649ce to your computer and use it in GitHub Desktop.
Save davidahouse/3269f60fe9a9d17649ce to your computer and use it in GitHub Desktop.
Playing around with Swift and subscripts
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"]
@kristopherjohnson
Copy link

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