Last active
August 22, 2019 22:25
-
-
Save krzyzanowskim/98093c6be7106192cd7b9b793ab7e34e to your computer and use it in GitHub Desktop.
Use typed keys
This file contains hidden or 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
// 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