在这种情况下我可以使用swift Generic吗?

时间:2015-02-01 12:07:42

标签: generics swift

我想将存储的属性添加到UIView子类中 UIView UIImageView UIPickerView 等,

我只需要从子类创建UIView的实例 子类仅在类型上有所不同,所有属性和方法都相同。 Type还符合几种协议。

class View: UIView, UIGestureRecognizerDelegate, ProtocolDelegate2 {
    var property1 = CGRectZero
    var property2:Int = 0
    var property3 = false

    func configView(config: [String:AnyObject]) {
        let recognizer = UIPanGestureRecognizer(target: self , action: Selector("panGestureHandler:"))

            recognizer.delegate = self
            addGestureRecognizer(recognizer)
    }

    func panGestureHandler(gestureRecognizer:UIPanGestureRecognizer)
    {

    }
}

class ImageView: UIImageView, UIGestureRecognizerDelegate, ProtocolDelegate2 {
    var property1 = CGRectZero
    var property2:Int = 0
    var property3 = false

    func configView(config: [String:AnyObject]) {
        let recognizer = UIPanGestureRecognizer(target: self , action: Selector("panGestureHandler:"))

            recognizer.delegate = self
            addGestureRecognizer(recognizer)
    }

    func panGestureHandler(gestureRecognizer:UIPanGestureRecognizer)
    {

    }
}

class PickerView: UIPickerView, UIGestureRecognizerDelegate, ProtocolDelegate2 {
    var property1 = CGRectZero
    var property2:Int = 0
    var property3 = false

    func configView(config: [String:AnyObject]) {
        let recognizer = UIPanGestureRecognizer(target: self , action: Selector("panGestureHandler:"))

            recognizer.delegate = self
            addGestureRecognizer(recognizer)
    }

    func panGestureHandler(gestureRecognizer:UIPanGestureRecognizer)
    {

    }
}

用法:

let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let imageView = ImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let pickerView = PickerView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

view.configView(config: JsonData)
view.alpha = 0.5

imageView.configView(config: JsonData)
imageView.alpha = 0.2

pickerView.configView(config: JsonData)
pickerView.backgroundColor = UIColor.orangeColor()

现在问题是,在这种情况下我们可以使用Swift Generics,因为类只在类型上有所不同。或者是否有更好的设计模式可以更好地维护代码。

1 个答案:

答案 0 :(得分:1)

如果你的类必须是UIView的子类,那么泛型不会帮助你。如果您尝试这样做:

class A<T: UIView> : T {  // ERROR
    var prop: String?
}

编译器抱怨T必须是类型或协议。

你可以这样做:

class A<T: UIView> {
    var theView: T
    var prop: String?
}

但这并不比简单地使用继承更好:

class A {
    var theView: UIView!
    var prop: String?

    init(view: UIView) {
        theView = view
    }
}