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:
let arrTest = someArray()
let
will make arrTest
immutable 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.
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.