use*_*711 1 functional-programming swift
我有一个包含几个字段的struct数组.我想映射数组以创建另一个包含字段子集的struct
struct History: {
let field1: String
let field2: String
let field3: String
let field4: String
}
struct SubHistory: {
let field1: String
let field2: String
}
Run Code Online (Sandbox Code Playgroud)
我可以使用for in循环.但是有可能使用地图,不是吗?
是的,您可以通过map以下方式使用:
let histories: [History] // array of History structs
let subHistories = histories.map { SubHistory(field1: $0.field1, field2: $0.field2) }
Run Code Online (Sandbox Code Playgroud)
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)
}
}
Run Code Online (Sandbox Code Playgroud)
Then the mapping can be simply done as
let histories: [History] = ...
let subHistories = histories.map(SubHistory.init)
Run Code Online (Sandbox Code Playgroud)
将初始化程序放入扩展中具有以下优点:默认的逐成员初始化程序仍然可以合成–此观察的属性归@kiwisip!