简体   繁体   English

Swift:我需要为函数返回创建一个新的不可变数组吗?

[英]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? 但是,在Swift中,由于数组是值类型,我是否仍然需要这样做?

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 let arrTest不可变
  2. var arrTest = someArray()
    • var will make arrTest mutable var将使arrTest可变

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. swift中的ArrayStruct ,而Struct是值类型,因此您的someArray()函数基本上会返回该数组的副本。
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. 通常只需迅速创建数组即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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