Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Find value in array and return specific key

Im new to swift and would appreciate your help..

Problem:

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.

My example:

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!

like image 777
phitsch Avatar asked Dec 18 '22 16:12

phitsch


1 Answers

Use flatMap:

let result = persons.flatMap {
    $0.hobbies.contains(StringToSearch) ? $0.name : nil
}
like image 132
Code Different Avatar answered Jan 05 '23 11:01

Code Different