Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with custom objects

Tags:

swift

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 ?

like image 552
Alexey K Avatar asked Oct 26 '25 05:10

Alexey K


2 Answers

try this:

var newArray : [Person] = array.filter {$0.age == 21}

map just modifies your array. it doesn't remove elements.

like image 84
Vyacheslav Avatar answered Oct 27 '25 23:10

Vyacheslav


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 })
like image 36
Sandeep Avatar answered Oct 27 '25 22:10

Sandeep