1
我已經基本上有兩種方法:陣列上的變化沒有被保存功能後
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.
所以它的副本?
謝謝!
這不起作用(出現錯誤) - 「無法轉換類型的值'數組'到期望的參數類型'inout Array '。這很可能是'arrayForService'方法返回一個數組的副本而不是實際引用任何bag數組的結果。嘗試一下,看看! –
royherma
@royherma你可以在這裏看看我的代碼:http://swiftstub.com/364381280。錯誤發生是因爲缺少&&。補充一點,你會很開心。 – ozgur
你的代碼執行的東西與我的非常不同,並且巧合地實現了類似的結果。想象你有幾個用戶數組(userA,userB等等),arrayForService(arg)返回一個基於arg的數組。然後您想要將一個包附加到從該方法返回的數組中。我在我的工具中測試了你的代碼,它仍然不起作用,因爲arrayForService返回一個副本,並且對副本的引用是副本,所以仍然沒有好處:( – royherma