Search code examples
arraysswiftsearchindexingcontains

Swift - Search in array if contains string and append to another array


I have an array:

let arr = ["Ivan Ivanov", "Bogdan Bogdanov", "Georgi Milchev", "Bogdan Petkov", "Vladimir Zahariev"]
let name = "Bogdan"

Search if array contains(name) and append the result to the new array without loop. So new array have to be ["Bogdan Bogdanov", "Bogdan Petkov"]

Trying with: if arr.contains(where: {$0 == name}) { newArray.append($0) }

but it's not working. Error: Anonymous closure argument not contained in a closure


Solution

  • You need

    let res = arr.compactMap { $0.contains(name) ? $0.components(separatedBy: " ").last! : nil  }