创建函数处理通用类型访问不同视图的属性

时间:2016-02-20 06:29:14

标签: ios swift generics swift2

我有2个观看次数,两者都有一些共同的属性:

class View1: UIView
{
    @IBOutlet weak var button1: UIButton
    @IBOutlet weak var button2: UIButton
}

class View2: UIView
{
    @IBOutlet weak var button1: UIButton
    @IBOutlet weak var button2: UIButton
}

class Utils {
    func enableButtons<T>(view: T) {
        if view is View1 {
            let tempView = view as View1
            tempView.button1.enabled = true
            tempView.button2.enabled = true

        } else if view is View2 {
            let tempView = view as View2
            tempView.button1.enabled = true
            tempView.button2.enabled = true
        }
    }
}

如何摆脱泛型函数enableButtons中的if-else语句,使其看起来像下面的内容,适用于作为参数发送的两个视图:

class Utils {
    func enableButtons<T>(view: T) {
        view.button1.enabled = true
        view.button2.enabled = true
    }
}

1 个答案:

答案 0 :(得分:1)

需要约束

T,以便编译器知道参数view有两个属性button1button2

为此,您需要使用协议。您可以使用该协议来显示两个视图的关联方式。因此,通用T可以知道两个按钮:

protocol TwoButtonView {

    weak var button1: UIButton! { get set }
    weak var button2: UIButton! { get set }

}

然后,让每个视图符合协议:

class View1: UIView, TwoButtonView


class View2: UIView, TwoButtonView

然后,重写enableButtons,以便T只能符合TwoButtonView协议:

func enableButtons<T: TwoButtonView>(view: T) {
    view.button1.enabled = true
    view.button2.enabled = true
}

修改

@DavidBerry指出,如果你走这条路,你不必使用泛型。相反,你可以这样做:

func enableButtons(view: TwoButtonView) {
    view.button1.enabled = true
    view.button2.enabled = true
}