I need to pass an array by reference (because the called function modifies it, and the changes should be reflected at the call site). Since Swift arrays are passed by value and NSArrays, by reference, I tried to declare the function as:
func save(_ photos: NSMutableArray<Photo>) {
But Xcode says I can't specialise a non-generic type NSMutableArray. So I have to do:
func save(_ photos: NSMutableArray) {
This loses type safety. Is there a way I can have both type safety and pass by value?
You cannot specialize NSMutableArray — only Objective-C can do that (ironic, isn't it?). However, you don't really need to.
Instead, simply declare photos
as inout [Photo]
. You will still be passing by value, but you will be able to write the modified array back to wherever it came from.
Simple example:
var originalArray = [1,2,3]
func modifyArray(_ array: inout [Int]) {
array = Array(array.dropFirst())
}
modifyArray(&originalArray)
originalArray // [2,3]