Swift: 返回对象的副本

Swift: Returning a copy of object

我需要使用 Swift return 一个对象的副本,但我不知道该怎么做。

这就是我在 Objective-C 中的做法:

-(NSArray*) doingSomethingwith
{
    NSArray *myArray = @[@"a",@"b",@"c",@"d",];

    return [myArray copy];
}

有人知道怎么做吗Swift?

非常感谢你的帮助。

Swift 不引用。所以,你可以直接return数组。

你可以这样做。

let myArray: NSArray = ["a","b","c","d"]

func returnCopyOfArray() -> NSArray{
return myArray
}

如果数组的内容是值对象,如您示例中的常量字符串,则只需 return 即可; Swift 分配有复制行为。 Classes And Structures Apple 文档末尾对此进行了解释:

Assignment and Copy Behavior for Strings, Arrays, and Dictionaries

In Swift, many basic data types such as String, Array, and Dictionary are implemented as structures. This means that data such as strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.

This behavior is different from Foundation: NSString, NSArray, and NSDictionary are implemented as classes, not structures. Strings, arrays, and dictionaries in Foundation are always assigned and passed around as a reference to an existing instance, rather than as a copy.

NOTE: The description above refers to the “copying” of strings, arrays, and dictionaries. The behavior you see in your code will always be as if a copy took place. However, Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so. Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimization.

如果您的数组包含引用对象,并且您想要 return 它们的深拷贝,那就有点棘手了; 关于如何处理。尽管正确的处理方法是重新编写代码以使用值类型。

好吧,您可以使对象符合 NSCopying。

class Person: NSObject, NSCopying {
var firstName: String
var lastName: String
var age: Int

init(firstName: String, lastName: String, age: Int) {
    self.firstName = firstName
    self.lastName = lastName
    self.age = age
}

func copy(with zone: NSZone? = nil) -> Any {
    let copy = Person(firstName: firstName, lastName: lastName, age: age)
    return copy
 }
}

然后就可以调用copy了。

let clone = myPerson.copy()

如果您没有实现 class,那么如果 class 具有 publicopen 访问权限,您可以潜在地扩展它。

extension Person: NSCopying {
  func copy(with zone: NSZone? = nil) -> Any {
    let copy = Person(firstName: firstName, lastName: lastName, age: age)
    return copy
 }
}