ios - 函数退出后不保留对数组的更改

标签 ios arrays swift

我基本上有两种方法:

private func addBagToCollection(bag : VendorBag){
    var array = arrayForService(bag.type)
    array.append(bag)
}

func arrayForService(type : BAG_TYPE) -> Array<VendorBag>{
        switch type{
        case .bagTypeDryCleaning:
            return dcBags
        case .bagTypeWashAndFold:
            return wfBags
        case .bagTypeLaunderedShirt:
            return lsBags
        case .bagTypeHangDry:
            return hdBags
        case .bagTypeUnknown:
            return unBags
        }
    }

问题是 addBagToCollection 中引用的数组没有保存附加项,这意味着每次我调用该方法时,数组的大小都是 0。

我在类的顶部初始化了我所有的数组:

var hdBags : Array<VendorBag> = [VendorBag]()
var wfBags : Array<VendorBag> = [VendorBag]()
var lsBags : Array<VendorBag> = [VendorBag]()
var dcBags : Array<VendorBag> = [VendorBag]()
var unBags : Array<VendorBag> = [VendorBag]()

但出于某种原因,arrayForService 函数似乎要么只返回数组的副本,要么返回新初始化的数组。我如何返回对该数组的引用,以便即使在退出该函数后仍保留对该数组所做的所有更改?

获得更多信息:

因此,从 functions 返回时,数组似乎确实被复制了--

Swift’s Array types are implemented as structures. This means that arrays 
are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.

那么如何返回对实际数组的引用而不是它的副本呢?

谢谢!

最佳答案

NSArray 类不同,Swift 数组是 struct 类型,这意味着它们在传递给函数时被复制。

来自 docs :

Note

Structures are always copied when they are passed around in your code, and do not use reference counting.

如果你想让你的数组通过引用传递,而不是通过复制,你需要使用关键字inout:

private func addBagToCollection(inout array: Array<VendorBag>, bag: VendorBag) {
  array.append(bag)
}

您可以按如下方式调用该函数:

addBagToCollection(&arrayForService(bag.type), bag)

关于ios - 函数退出后不保留对数组的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553468/

相关文章:

自定义 UIActivityType 的 Objective-C 版本

android - 将移动应用程序 bundle 到单个下载中

ios - 自动布局 - 中间有 5 个按钮

ios - 即使在优步应用程序被删除后,优步指纹 iPhone 如何识别它们?

c# - 如何按升序显示文本文件中的数据#

javascript - 使用javascript在括号内添加字符串

ios - 在 xcode 中编辑意图方案时,Siri 意图查询输入字段不可用

ios - EAS 构建 - rsync 错误 : some files could not be transferred (code 23) error

c - 使指针指向整数而不进行强制转换

ios - swift 3 使用图层通过绘制 "clear"行来显示图像