This is syntactic sugar around your solution, @AdamBardon.
You can extend Array to allow you to subscript it directly. Under the covers it is just using the same first(where:) call:
protocol HasKey {
var key: String { get }
}
struct Struct: HasKey {
var key: String
var value: Int
}
extension Array where Element: HasKey {
subscript(str: String) -> Element? {
return self.first(where: { $0.key == str })
}
}
Example:
let array = [Struct(key: "a", value: 1), Struct(key: "b", value:2)]
if let x = array["a"] {
print(x)
}
Output:
Struct(key: "a", value: 1)
Using the protocol allows you to easily extend this functionality to any class or struct that has a key: String property by having them adopt the HasKey property:
extension SomeOtherClass: HasKey { }
You can also accomplish it without the protocol by checking if Element == Struct:
extension Array where Element == Struct {
subscript(str: String) -> Element? {
return self.first(where: { $0.key == str })
}
}