0
我有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
}
}
差不多了,注意,實在沒有理由在這種情況下,通用,只需使用:'FUNC enableButtons(查看:TwoButtonView){...}' –
@DavidBerry是,但OP想要泛型,所以我給了他泛型。泛型是有用的,但有時它們過於複雜。 – tktsubota
我認爲他只是想要仿製藥,因爲這就是他最初的方式,但也許:) –