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 { ... }}

tips & tricks

Join 7,714 other subscribers

interview questions


Algorithm Android Android Studio API APP Programming Apps AS400 blogging Browser CheatSheets Config CSS DATABASE dsa error Features GUI HTML HTML5 IDE installation Interview Questions IOS iPhone javascript Mac objective-c OneDrive OS Programming quicktips SDK SEO Settings SMO SQL swift swiftUI Teams Tips & Tricks Tools UI Web Wordpress Xcode


Archives

Discover more from CODE t!ps

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

Continue reading