use*_*800 0 arrays initialization swift
标题很长,但我认为这最能概括我的问题。
给定一个整数n,我想用最多包含 n 个对象。
问题是数组中的对象不能为nil,但是,对象类型的构造函数可能会失败(即返回 nil)。
我想出了两种方法来解决这个问题,我认为还有更多 - 是否有比以下两种常见的、良好的实践、众所周知或更好的解决方案?
struct MyClass {
init?() {
// ...
if (/* cond */) { return nil }
}
}
// ...
// 1. solution
struct A {
let arr: [MyClass]
let n = 6
init?() {
let arr = (0..<n).map { _ in MyClass() }
guard arr.allSatisfy({ $0 != nil }) else { return nil }
self.arr = arr as! [MyClass] // At this point we can safely force-cast
}
}
// 2. solution
struct A {
let arr: [MyClass]
let n = 6
init() {
self.arr = (0..<n).map { _ in MyClass() }.reduce(into: []) { segments, segment in
if let segment = segment {
segments.append(segment)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你需要compactMap.
self.arr = (0..<n).compactMap { _ in MyClass() }
Run Code Online (Sandbox Code Playgroud)
compactMap接受一个返回一个可选项的闭包,并返回一个过滤掉所有 nils 的数组。如果我理解正确的话,这应该正是您想要的。
| 归档时间: |
|
| 查看次数: |
29 次 |
| 最近记录: |