我想知道有没有更优雅的写法:
struct S {
var state: [String: Any]
public var amounts: [Amount] {
var result: [Amount] = []
(self.state["amounts"] as? [Any]?)??.forEach({ a in
result.append(Amount(a))
})
return result
}
}
struct Amount {
init(_ any: Any?) {}
}
我尝试过使用 map
作为数组,但我找不到这样做的方法。
最佳答案
你也可以使用 guard let
和 early return,这样看起来会好一些。
我是这样做的
struct S {
var state: [String: Any]
public var amounts: [Amount] {
guard let amounts = state["amounts"] as? [Any] else {
return []
}
return amounts.map(Amount.init)
}
}
关于ios - Swift:写这个数组映射的更优雅的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181269/