我基本上有两种方法:
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/