itenyh itenyh - 1 month ago 6
Swift Question

How to declare a parameter that implements several protocol

I have a custom UIView which contains an UIPickerView. What I want to do now is to create a function to pass a parameter as the delegate of the UIPickerView:

class MQPickerView: UIView {

let pickerView = UIPickerView()

......

func setDelegate(delegate: AnyObject) {

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

}

}


I try the type AnyObject at first, but it can not be passed to dataSource and delegate of pickerView. How can I declare the paramter type to express that I need a parameter which implements the dataSource and delegate of pickerView?

Answer

You can use generic parameter with where clause like this:

Swift 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)  {}      
Comments