简体   繁体   中英

How do I declare an NSArray of a specific type in Swift?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM