Created
October 6, 2017 16:05
-
-
Save mikeash/bf401ee51a6ab060bcdcbdafed02b3c0 to your computer and use it in GitHub Desktop.
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
protocol TSDKey { | |
associatedtype Value | |
static var defaultValue: Value { get } | |
} | |
struct TSD { | |
private var storage: [ObjectIdentifier: Any] = [:] | |
subscript<Key: TSDKey>(key: Key.Type) -> Key.Value { | |
get { | |
return storage[ObjectIdentifier(key)] as? Key.Value ?? Key.defaultValue | |
} | |
set { | |
storage[ObjectIdentifier(key)] = newValue | |
} | |
} | |
} | |
enum Name: TSDKey { | |
static var defaultValue = "" | |
} | |
enum Age: TSDKey { | |
static var defaultValue: Int? = nil | |
} | |
var d = TSD() | |
d[Name.self] = "Thingy" | |
d[Name.self] | |
d[Age.self] | |
d[Age.self] = 42 | |
d[Age.self] | |
d[Name.self].append("doodle") | |
d[Name.self] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment