Skip to content

Instantly share code, notes, and snippets.

@PatrikTheDev
Last active April 24, 2020 08:22
Show Gist options
  • Save PatrikTheDev/d9dc7d014795c51d142b64b84163ae0f to your computer and use it in GitHub Desktop.
Save PatrikTheDev/d9dc7d014795c51d142b64b84163ae0f to your computer and use it in GitHub Desktop.
Array as a dictionary
struct Model {
var id: String
var value: Int
}
var arrAsDict = [
Model(id: "foo", value: 2),
Model(id: "bar", value: 5)
]
extension Array where Element == Model {
subscript(_ id: String) -> Model? {
filter { $0.id == id }.first
}
subscript(_ model: Model) -> String? {
filter { $0.id == model.id }.first?.id
}
}
print(arrAsDict["foo"]?.value)
print(arrAsDict["bar"]?.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment