如何符合NSCopying并在Swift 2中实现copyWithZone?

如何符合NSCopying并在Swift 2中实现copyWithZone?,第1张

概述我想在 Swift 2中实现一个简单的GKGameModel.苹果的例子在Objective-C中表达,并包含这个方法声明(根据GKGameModel继承的NSCopying协议的要求): - (id)copyWithZone:(NSZone *)zone { AAPLBoard *copy = [[[self class] allocWithZone:zone] init]; [ 我想在 Swift 2中实现一个简单的GKGameModel.苹果的例子在Objective-C中表达,并包含这个方法声明(根据GKGameModel继承的NScopying协议的要求):
- (ID)copyWithZone:(NSZone *)zone {    AAPLBoard *copy = [[[self class] allocWithZone:zone] init];    [copy setGameModel:self];    return copy;}

这怎么翻译成Swift 2?在效率和忽视区方面是否适合?

func copyWithZone(zone: NSZone) -> AnyObject {    let copy = GameModel()    // ... copy propertIEs    return copy}
NSZone已经不再在Objective-C中使用了很长时间.而传递的区域参数被忽略.从allocWithZone引用… docs:

This method exists for historical reasons; memory zones are no longer
used by Objective-C.

你也可以忽略它.

下面是一个如何符合NScopying协议的例子.

class GameModel: NSObject,NScopying {  var someProperty: Int = 0  required overrIDe init() {    // This initializer must be required,because another    // initializer `init(_ model: GameModel)` is required    // too and we would like to instantiate `GameModel`    // with simple `GameModel()` as well.  }  required init(_ model: GameModel) {    // This initializer must be required unless `GameModel`    // class is `final`    someProperty = model.someProperty  }  func copyWithZone(zone: NSZone) -> AnyObject {    // This is the reason why `init(_ model: GameModel)`    // must be required,because `GameModel` is not `final`.    return self.dynamicType.init(self)  }}let model = GameModel()model.someProperty = 10let modelcopy = GameModel(model)modelcopy.someProperty = 20let anotherModelcopy = modelcopy.copy() as! GameModelanotherModelcopy.someProperty = 30print(model.someProperty)             // 10print(modelcopy.someProperty)         // 20print(anotherModelcopy.someProperty)  // 30

附:此示例适用于Xcode Version 7.0 beta 5(7A176x).特别是dynamicType.init(self).

为Swift 3编辑

以下是Swift 3的copyWithZone方法实现,因为dynamicType已被弃用:

func copy(with zone: NSZone? = nil) -> Any{    return type(of:self).init(self)}
总结

以上是内存溢出为你收集整理的如何符合NSCopying并在Swift 2中实现copyWithZone?全部内容,希望文章能够帮你解决如何符合NSCopying并在Swift 2中实现copyWithZone?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1026994.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-23
下一篇2022-05-23

发表评论

登录后才能评论

评论列表(0条)

    保存