Skip to content

Instantly share code, notes, and snippets.

@mikeash
Created October 6, 2017 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeash/bf401ee51a6ab060bcdcbdafed02b3c0 to your computer and use it in GitHub Desktop.
Save mikeash/bf401ee51a6ab060bcdcbdafed02b3c0 to your computer and use it in GitHub Desktop.
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