Class conforming to protocol as function parameter in Swift
swift
Solution
You can define `foo` as a generic function and use type constraints to require both a class and a protocol.
Swift 4
func foo<T: UIViewController & UITableViewDataSource>(vc: T) {
.....
}
Swift 3 (works for Swift 4 also)
func foo<T: UIViewController>(vc:T) where T:UITableViewDataSource {
....
}
Swift 2
func foo<T: UIViewController where T: UITableViewDataSource>(vc: T) {
// access UIViewController property
let view = vc.view
// call UITableViewDataSource method
let sections = vc.numberOfSectionsInTableView?(tableView)
}
Problem
In Objective-C, it's possible to specify a class conforming to a protocol as a method parameter. For example, I could have a method that only allows a `UIViewController` that conforms to `UITableViewDataSource`: ``` - (void)foo:(UIViewController<UITableViewDataSource> *)vc; ``` I can't find a way to do this in Swift (perhaps it's not possible yet). You can specify multiple protocols using `func foo(obj: protocol<P1, P2>)`, but how do you require that the object is of a particular class as well?