gpt4 book ai didi

swift - 在一个循环中初始化多个不可变数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:38 25 4
gpt4 key购买 nike

这是我的代码:

class Birthgiver {}
class Son: Birthgiver {}
class Daughter: Birthgiver {}

class BirthgiverHolder {
let sons: [Son]
let daughters: [Daughter]

init(birthGivers: [Birthgiver]) {
// How to initializer both sons and daugthers in 1 loop?
// This is my current way (looping twice):
sons = birthGivers.compactMap { $0 as? Son }
daughters = birthGivers.compactMap { $0 as? Daughter }
}
}

我在数组 birthGivers 上循环两次。有什么方法可以初始化儿子和女儿而只循环一次 birthGivers?我不想将数组标记为 vars

最佳答案

选项 1:拥有本地变量并在完成后填充常量:

init(birthGivers: [Birthgiver]) {
var sons: [Son] = []
var daughters: [Daughter] = []

for child in birthGivers {
switch child {
case let son as Son: sons.append(son)
case let daughter as Daughter: daughters.append(daughter)
default: break
}
}

self.sons = sons
self.daughters = daughters
}

选项 2:您也可以使用 reduce(into:) 实现它(尽管我个人认为上面的代码更具可读性):

init(birthGivers: [Birthgiver]) {
(sons, daughters) = birthGivers.reduce(into: ([], [])) {
switch $1 {
case let son as Son: $0.0.append(son)
case let daughter as Daughter: $0.1.append(daughter)
default: break
}
}
}

选项 3:坚持使用 compactMap 方法:

init(birthGivers: [Birthgiver]) {
sons = birthGivers.compactMap { $0 as? Son }
daughters = birthGivers.compactMap { $0 as? Daughter }
}

在大多数情况下,最后一个选项就足够了。您需要大量记录才能观察到性能差异。

关于swift - 在一个循环中初始化多个不可变数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55695482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com