Skip to content

Instantly share code, notes, and snippets.

@westerlund
Created April 21, 2015 15:08
Show Gist options
  • Save westerlund/7eaeb8115062a5c24e3b to your computer and use it in GitHub Desktop.
Save westerlund/7eaeb8115062a5c24e3b to your computer and use it in GitHub Desktop.
Attempted to implement ValueForKey in Swift
class SomeClass {
var a: String?
var b: [Int]?
private func _u(named: String, value: AnyObject?, set: Bool) -> AnyObject? {
switch named {
case "a":
if set {
a = value as? String
} else {
return a
}
case "b":
if set {
b = value as? [Int]
} else {
return b
}
default:
fatalError("Property named '\(named)' doesn't exist")
}
return nil
}
subscript(index: String) -> AnyObject? {
get { return _u(index, value: nil, set: false) }
set(newValue) { _u(index, value: newValue, set: true) }
}
}
var t = SomeClass()
t["b"] = [1, 2, 3]
t["a"] = "monkey"
//t["x"] = 12 // crashes
println(t.a) // prints monkey
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment