我想在
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:
原文链接:https://www.f2er.com/swift/318829.htmlThis 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 = 10 let modelCopy = GameModel(model) modelCopy.someProperty = 20 let anotherModelCopy = modelCopy.copy() as! GameModel anotherModelCopy.someProperty = 30 print(model.someProperty) // 10 print(modelCopy.someProperty) // 20 print(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) }