Swift中返回不可变数组时,是否需创建新的不可变数组?
Great question! Let’s break this down by comparing Objective-C and Swift’s core behaviors, since that’s where your confusion is rooted.
Why Objective-C requires the copy approach
In Objective-C, NSMutableArray and NSArray are reference types. This means when you return the mutable array directly, you’re handing the caller a reference to the exact same array instance. A caller could easily cast it back to NSMutableArray and modify it, breaking the encapsulation you intended by returning an "immutable" array.
That’s why the standard practice is to return array.copy—this creates a new immutable NSArray instance, ensuring the caller can’t tamper with the original mutable array you built locally.
Why Swift doesn’t need the same workaround
Swift arrays are value types, not reference types. When you return a value type (like [MyValue]), Swift automatically handles copying (using copy-on-write optimization to avoid unnecessary overhead until the value is modified).
Take your example:
func someArray() -> [MyValue] { var array = [MyValue]() // ... modify array as needed return array // This is totally safe! }
Here’s what’s happening under the hood:
- Even though
arrayis declared asvar(mutable), returning it gives the caller a copy of the array. - If the caller assigns the result to a
letconstant, they can’t modify it at all. - If they assign it to a
var, any changes they make will only affect their own copy—your original localarrayremains untouched.
Is return Array(array) necessary?
No, this is completely redundant. Array(array) creates an extra copy of the array, but Swift already copies the value when returning it. This adds unnecessary work without any extra safety benefits, so there’s no reason to use it.
Key takeaway
In Swift, you can safely return your mutable local array directly. The language’s value type semantics guarantee that the caller can’t modify the original array you built inside the function—so you don’t need to explicitly copy it like you did in Objective-C.
内容的提问来源于stack exchange,提问作者Heuristic

