2015年12月17日 星期四

一個關於遵循多個Swift 2.0 protocol extension的問題

問題

最近練習用Protocol-Oriented Programming實做可移動以及縮放的View,遇到一個很有趣的問題,假設有以下兩個protocol

protocol Draggable: class {
    var view: UIView { get }
    var initialLocation: CGPoint { get set }
}

extension Draggable where Self: UIView {
    var view: UIView { get { return self } }
    var parentView: UIView? { get { return self.view.superview } }
}
protocol Scalable: class {
    var view: UIView { get }
}

extension Scalable where Self: UIView {
    var view: UIView { get { return self } }
    var parentView: UIView? { get { return self.view.superview } }
}

然後實做一個View遵循這兩個protocol

public class VWView: UIView, Draggable, Scalable {
    var initialLocation: CGPoint = CGPointZero
}

這時候會發生compile error,告訴你
Type 'VWView' does not conform to protocol 'Scalable'
Type 'VWView' does not conform to protocol 'Draggable'

怎麼一回事呢?

原來是因為兩個protocol都有var view: UIView { get { return self } }的default implementations,編譯器不曉得該用哪一個,乾脆來一個編譯錯誤。

解法

其實解決方法很簡單,就是在class裡實做這個值,這樣編譯器就知道該用class裡面的這個了。

public class VWView: UIView, Draggable, Scalable {
    var view: UIView { get { return self } }
    var initialLocation: CGPoint = CGPointZero
}

Reference:
http://stackoverflow.com/questions/31586864/swift-2-0-protocol-extensions-two-protocols-with-the-same-function-signature-c

沒有留言:

張貼留言