Created
April 21, 2015 15:08
-
-
Save westerlund/7eaeb8115062a5c24e3b to your computer and use it in GitHub Desktop.
Attempted to implement ValueForKey in Swift
This file contains 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
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