Im new to swift and would appreciate your help..
In my future project I would love to look for a specific String in an Array and get only the names back who have this value in their hobbies Array.
struct Person {
var name: String
var hobbies:Set <String>
}
var persons: [Person]
persons = [
Person(name: "Steve", hobbies: ["PC", "PS4", "Gaming", "Basketball"]),
Person(name: "Max", hobbies: ["Gaming", "Xbox", "cooking", "PC"]),
Person(name: "Julia", hobbies: ["Soccer", "Tennis", "cooking", "Painting"])
]
var StringToSearch = "PC"
I would love to get only the names back who hobbies "PC" is. How can I iterate through my collection and get only the keys instead of the values back like in a dictionary? Thank you!
Use flatMap
:
let result = persons.flatMap {
$0.hobbies.contains(StringToSearch) ? $0.name : nil
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With