Victor S. Wang
user

Victor S. Wang

startup, freelancer, developer, technology enthusiasts, innovation, passion


Featured

Swift

Two weird things about protocol, extension and subclass in Swift

Posted by Victor S. Wang on .

As I wrote a post about method dispatch in Swift yesterday, in the meantime, I found there are two weird problems.

Tested with Swift 2.1 & Xcode 7.2

The first one is the behaviors of overriding extension method are weird. It seems that we can only override the methods in extension which is full compatible with Objective-C. Otherwise we’ll have an compile error: Declaration from extensions cannot be overridden yet

See the code below: - This will work

typealias Style = String

protocol Draggable {}

extension UIView: Draggable {
    func drag() {}
    func drag(with style: Style) {}
}

class MyDraggableView: UIView {
    override func drag() {}
    override func drag(with style: Style) {}
}
  • This won’t work
struct Style {}

protocol Draggable {}

extension UIView: Draggable {
    func drag() {}
    func drag(with style: Style) {}
}

class MyDraggableView: UIView {
    override func drag() {}
    override func drag(with style: Style) {} // compiler error: Declaration from extensions cannot be overridden yet
}

On StackOverflow, there is also a question relevant. But I still don’t know what’s the reason behind, what’s the original purpose if there was one.

The second one is probably a bug, the code below will crash everytime the source editor in Playground, and give a segment error in Xcode 7.2

protocol Draggable {
    func drag()
}

extension Draggable {
    func drag(with style: String) {} // just rename drag to another name will fix the problem
}

extension UIView: Draggable {}

If you have any idea, please tell me on twitter @wangshengjia.

Thanks.

user

Victor S. Wang

www.allblue.me

startup, freelancer, developer, technology enthusiasts, innovation, passion