I have some objects
let one = Person(name: "Joe", age:20)
let two = Person(name: "Phil", age:21)
let three = Person(name: "Moe", age:21)
then I have an array
let array = [one, two, three]
now I need to create a new array, that will contain only persons whose age is 21.
I try
var newArray : [Person] = array.map ({ $0.age = 21 })
but compiler says that he can't convert result type '_?' to expected type [Person]
What am I doing wrong ?
try this:
var newArray : [Person] = array.filter {$0.age == 21}
map just modifies your array. it doesn't remove elements.
Map is not what your are expecting to do. Map creates a new array from the array.
let one = Person(name: "Joe", age:20)
let two = Person(name: "Phil", age:21)
let three = Person(name: "Moe", age:21)
let array = [one, two, three]
var newArray : [Int] = array.map ({ $0.age })
Returns a new array, containing age of all people. [20, 21, 21]
I think you are probably after filter method,
var newArray : [Person] = array.filter ({ $0.age == 21 })
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