Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map an array of struct

I have an array of struct containing several fields. I want to map the array to create another one of struct containing a subset of fields

struct History: {
   let field1: String
   let field2: String
   let field3: String
   let field4: String
}

struct SubHistory: {
   let field1: String
   let field2: String
}

I could use the for in loop. But It may be possible to use a map, no ?

like image 852
user3239711 Avatar asked Mar 21 '26 06:03

user3239711


2 Answers

Yes, you can use map in the following way:

let histories: [History] // array of History structs
let subHistories = histories.map { SubHistory(field1: $0.field1, field2: $0.field2) }
like image 126
kiwisip Avatar answered Mar 23 '26 23:03

kiwisip


As a slight variation of kiwisip's correct answer: I would suggest to put the logic of “creating a SubHistory from a History” into a custom initializer:

extension SubHistory {
    init(history: History) {
        self.init(field1: history.field1, field2: history.field2)
    }
}

Then the mapping can be simply done as

let histories: [History] = ...
let subHistories = histories.map(SubHistory.init)

Putting the initializer into an extension has the advantage that the default memberwise initializer is still synthesized – attribution for this observation goes to @kiwisip!

like image 31
Martin R Avatar answered Mar 23 '26 22:03

Martin R