ios - 如何最好地管理 Swift 中的可选数组?

标签 ios arrays swift option-type

我希望管理一系列选项并实现以下行为:

用 nil 初始化为某个常量大小(为了简洁,将使用泛型类型 T):

var myRay = [T?](repeating: nil, count: 5)

所以我们有:[nil,nil,nil,nil,nil]

我想要一个函数从头开始向该数组添加项目,并随时替换 nil 值。当数组填满非零值后,该函数会将值添加到数组的末尾。

因此,如果我们在上面的数组上调用此函数 7 次,它将如下所示:

insert(item: T, array: inout [T]?)

x1: [X, nil, nil, nil, nil]
x2: [X, X, nil, nil, nil]
x3: [X, X, X, nil, nil]
x4: [X, X, X, X, nil]
x5: [X, X, X, X, X]
x6: [X, X, X, X, X, X]
x7: [X, X, X, X, X, X, X]  

(其中 X 是非零值)

我提出了以下有效的解决方案。我之所以把它扔在那里,是因为我认为很可能有一个更好的解决方案,而且我认为这是一个非常有趣的问题,出现在像 swift 这样具有选项的语言中。下面发布我的解决方案:

private func insertValue<T>(element: T, array: inout [T?]) {
    let insertIndex = getFirstNilIndex(fromArray: array)
    array.insert(element, at: insertIndex)

    if let lastElement = array.last, let _ = lastElement {
        // the last element is a non-nil value of type T
    } else {
        // the last element is nil
        array.remove(at: array.endIndex - 1)
    }
}

// returns index of first nil object in array, or the end index if the array does not contain any nil values
private func getFirstNilIndex<T>(fromArray array: [T?]) -> Int {
    for (index, item) in array.enumerated() {
        if item == nil {
            return index
        }
    }
    return array.endIndex
}

这是由于一种奇怪的情况而起作用的,我们有一个双层包装的可选值。 Array.last 返回一个可选值,当它返回的非零值本身就是一个可选值时,您必须重新打开该值!我认为这行不通,因为我不知道 Swift 是否会区分 .some(.none) 和 .none。

所以我向你们所有人提出的问题是,你们能找到更好或更“快捷”的方法来实现这一目标吗?您觉得这个解决方案怎么样?您能否推荐一种不同的方法,或者您对语言的这方面是否有任何信息丰富的评论,以帮助我更清楚地理解这个过程?

最佳答案

  • 现有的 index(where:) 方法可用于查找第一个 nil 条目的索引。
  • 如果找到 nil 元素,则替换该条目,否则 追加一个条目。

这比总是插入新条目然后检查更简单 是否应删除最后一个元素。

func insertValue<T>(element: T, array: inout [T?]) {

    if let idx = array.index(where: { $0 == nil } ) {
        array[idx] = element
    } else {
        array.append(element)
    }
}

关于ios - 如何最好地管理 Swift 中的可选数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44579184/

相关文章:

ios - 尝试访问已注册单元格的成员时出现运行时错误

.NET矩形数组: how to access in a loop?

arrays - 在 2D numpy 数组的每个滚动窗口中获得最大值

ios - 展开后,在 Xcode 中取消 View 修改

ios - 如果第一个通知在 swift 中被忽略,则安排第二个通知(或者如果通知被忽略则完成任何操作)

javascript - iOS 应用程序,在浏览器中打开网站的链接,网站中的链接关闭浏览器

ios - 保存由结构体对象数组组成的 Realm 列表

ios - UISearchController 搜索两个数组

ios - TabBar 叠加在 View 上 - IOS

c - scanf("%number[^\n], array[N].struct) 的字符串长度