如何声明实现多个协议的参数

时间:2016-10-26 08:08:33

标签: ios swift

我有一个包含UIPickerView的自定义UIView。我现在要做的是创建一个函数来传递参数作为UIPickerView的委托:

class MQPickerView: UIView {

    let pickerView = UIPickerView()

     ......

    func setDelegate(delegate: AnyObject) {

        self.pickerView.dataSource = delegate
        self.pickerView.delegate = delegate

    }

}

我首先尝试使用AnyObject类型,但它不能传递给pickerView的dataSource和delegate。如何声明参数类型来表示我需要一个实现pickerView的dataSource和委托的参数?

1 个答案:

答案 0 :(得分:2)

您可以将泛型参数与where子句一起使用,如下所示:

斯威夫特3:

func setDelegate<T>(delegate: T) where T: UIPickerViewDelegate, T:UIPickerViewDataSource {
    self.pickerView.dataSource = delegate
    self.pickerView.delegate = delegate
}

Swift 2:

 func setDelegate<T where T: UIPickerViewDelegate, T:UIPickerViewDataSource>(delegate: T)  {}