Last active
April 24, 2020 08:22
-
-
Save PatrikTheDev/d9dc7d014795c51d142b64b84163ae0f to your computer and use it in GitHub Desktop.
Array as a dictionary
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
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