我正在尝试创建一个将为 View Controller 提供数据的协议(protocol)。我正在尝试采用协议(protocol)方法并使事情变得灵活,因此 View Controller 可以使用任何类型的数据。
但是,我收到错误:Protocol 'Serviceable' can only be used as a generic contraint because it has Self or associated type requirements
这就是我想要做的:
protocol Serviceable {
associatedtype DataType
func get(handler: ([DataType] -> Void)?)
}
struct PostService: Serviceable {
func get(handler: ([Postable] -> Void)? = nil) {
print("Do something...")
}
}
struct AuthorService: Serviceable {
func get(handler: ([Authorable] -> Void)? = nil) {
print("Do something...")
}
}
protocol Postable {
var title: String { get set }
var content: String { get set }
}
protocol ServiceControllable: class {
var service: Serviceable { get } // Error: Protocol 'Serviceable' can only be used as a generic contraint because it has Self or associated type requirements
}
extension ServiceControllable {
func setupDataSource() {
service.get { items in
// Do something
}
}
}
class MyViewController: ServiceControllable {
let service: Serviceable = PostService() // Error: Same as above
override func viewDidLoad() {
super.viewDidLoad()
setupDataSource()
}
}
如何设置它以便我的 View Controller 可以实现 ServiceControllable 并可以访问填充表、集合等的通用 setupDataSource?
最佳答案
你想要这样的东西。
import UIKit
protocol Serviceable {
associatedtype DataType
func get(handler: ([DataType] -> Void)?)
}
struct PostService: Serviceable {
func get(handler: ([Postable] -> Void)? = nil) {
print("Do something...")
}
}
protocol Authorable {}
struct AuthorService: Serviceable {
func get(handler: ([Authorable] -> Void)? = nil) {
print("Do something...")
}
}
protocol Postable {
var title: String { get set }
var content: String { get set }
}
protocol ServiceControllable: class {
// THIS is the way to use generic-constraint-protocols in protocols.
associatedtype _Serviceable: Serviceable
var service: _Serviceable { get }
}
extension ServiceControllable {
func setupDataSource() {
service.get { items in
// Do something
}
}
}
class MyViewController: UIViewController, ServiceControllable {
let service = PostService()
override func viewDidLoad() {
super.viewDidLoad()
setupDataSource()
}
}
相关文档部分:Protocol Associated Type Declaratio .
关于ios - 如何创建面向协议(protocol)的通用服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36840093/