初始化给定大小 n 的 non-optional object 数组,其中 object 的初始化程序可能会失败

Initialise an array of non-optional objects with a given size n where the object's initialiser may fail

标题很长,但我认为这最能概括我的问题。

给定一个整数 n,我想用 最多 n objects 初始化一个数组。

问题是数组中的 objects 不能为 nil,但是,object 类型的构造函数可能会失败(即 return nil ).

我想到了两种方法来解决这个问题,而且我认为还有更多 - 是否有共同的 good-practice、well-known 或比以下两个更好的解决方案?

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({ [=12=] != 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)
      }
    }
  }
}

你需要compactMap.

self.arr = (0..<n).compactMap { _ in MyClass() }

compactMap 接受一个闭包,returns 一个可选的,returns 一个过滤掉所有 nils 的数组。如果我没有理解错的话,这应该正是你想要的。