Overriding methods and conforming to protocols in swift

Overriding methods and conforming to protocols in swiftOverriding methods and conforming to protocols in swift

When subclassing an Objective-C class and overriding its methods, or conforming to an Objective-C protocol, the type signatures of methods need to be updated when the parent method uses id in Objective-C. Some common examples are the NSObject class’s isEqual: method and the NSCopying protocol’s copyWithZone: method. In Swift 2, you would write a subclass of NSObject conforming to NSCopying like this:

// Swift 2class Foo: NSObject, NSCopying { override func isEqual(_ x: AnyObject?) -> Bool { ... } func copyWithZone(_ zone: NSZone?) -> AnyObject { ... }}

In Swift 3, in addition to making the naming change from copyWithZone(_:) to copy(with:), you will also need to change the signatures of these methods to use Any instead of AnyObject:

// Swift 3class Foo: NSObject, NSCopying { override func isEqual(_ x: Any?) -> Bool { ... } func copy(with zone: NSZone?) -> Any { ... }}

Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top