Class conforming to protocol as function parameter in Swift

前端 未结 7 1249
萌比男神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:43

    You can define foo as a generic function and use type constraints to require both a class and a protocol.

    Swift 4

    func foo(vc: T) {
        .....
    }
    

    Swift 3 (works for Swift 4 also)

    func foo(vc:T) where T:UITableViewDataSource { 
        ....
    }
    

    Swift 2

    func foo(vc: T) {
        // access UIViewController property
        let view = vc.view
        // call UITableViewDataSource method
        let sections = vc.numberOfSectionsInTableView?(tableView)
    }
    

提交回复
热议问题