Class conforming to protocol as function parameter in Swift

前端 未结 7 1246
萌比男神i
萌比男神i 2020-11-29 02:12

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 UIViewControlle

相关标签:
7条回答
  • 2020-11-29 02:55

    What about this way?:

    protocol MyProtocol {
        func getTableViewDataSource() -> UITableViewDataSource
        func getViewController() -> UIViewController
    }
    
    class MyVC : UIViewController, UITableViewDataSource, MyProtocol {
    
        // ...
    
        func getTableViewDataSource() -> UITableViewDataSource {
            return self
        }
    
        func getViewController() -> UIViewController {
            return self
        }
    }
    
    func foo(_ vc:MyProtocol) {
        vc.getTableViewDataSource() // working with UITableViewDataSource stuff
        vc.getViewController() // working with UIViewController stuff
    }
    
    0 讨论(0)
提交回复
热议问题