Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active August 22, 2019 22:25
Show Gist options
  • Save krzyzanowskim/98093c6be7106192cd7b9b793ab7e34e to your computer and use it in GitHub Desktop.
Save krzyzanowskim/98093c6be7106192cd7b9b793ab7e34e to your computer and use it in GitHub Desktop.
Use typed keys
// instead doing this
let dict: Dictionary<String, Any> = [:]
dict["name"] = "Marcin"
// do this if it's closed set
enum Keys: String, CaseIterable {
case name, address
}
// or this if it's open set
struct Keys: Hashable, RawRepresentable {
let rawValue: String
init?(rawValue: String) {
self.rawValue = rawValue
}
static let name = Keys(rawValue: "name")!
static let address = Keys(rawValue: "address")!
}
extension Encodable where Self == Keys {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
// and you're safer
var dict: Dictionary<Keys, Any> = [:]
dict[.name] = "Marcin"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment