我有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
}
}
答案 0 :(得分:1)
T
,以便编译器知道参数view
有两个属性button1
和button2
。
为此,您需要使用协议。您可以使用该协议来显示两个视图的关联方式。因此,通用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
}