简体   繁体   中英

Swift: do I need to create a new immutable array for function return?

Say a function/method has a local mutable array and the return type of the function/method is an immutable array. It's a common practice to create a new immutable array to be returned:

- (NSArray *)someArray {
    NSMutableArray *array = [NSMutableArray array]
    // ...do something with array
    return array.copy
}

However, in Swift, since the array is a value type, do I still need to do the same?

func someArray() -> [MyValue] {
    var array = [MyValue]()
    // do something with array
    return array // or return Array(array)?
}

For your example:

func someArray() -> [MyValue] {
    var array = [MyValue]()

    //...do something with array
    return array
}

It will depend on how you use the function.

If you do:

  1. let arrTest = someArray()
    • let will make arrTest immutable
  2. var arrTest = someArray()
    • var will make arrTest mutable

Array s in swift are Struct s, and Struct s are value types so your function someArray() is basically returning a copy of the array.
The creation of the array inside the function doesn't determine it's mutability.


So to answer your question:

No! You don't need to do the same.
Just create the array normally in swift.

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