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 ?
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) }
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!
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