仅类协议作为具有AnyObject约束的关联类型的类型

时间:2018-05-25 16:57:07

标签: swift class generics protocols anyobject

在Swift 4.0中我可以写这样的东西

protocol ObserversHolder {

    ///Compiling Error in Swift 4.1
    ///note: possibly intended match 'StringManager.ObserverValue' (aka 'StringObserver') does not conform to 'AnyObject'
    ///note: protocol requires nested type 'ObserverValue'; do you want to add it?
    associatedtype ObserverValue: AnyObject

    var observers: [ObserverValue] {get set}
}

protocol StringObserver: class {
    func showString()
}

class StringManager: ObserversHolder {
    typealias ObserverValue = StringObserver

    var observers = [ObserverValue]()
}

但是在Swift 4.1中我收到错误Type 'StringManager' does not conform to protocol 'ObserversHolder'

有可能解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

AnyObject更改为Any

protocol ObserversHolder {

    ///Compiling Error in Swift 4.1
    ///note: possibly intended match 'StringManager.ObserverValue' (aka 'StringObserver') does not conform to 'AnyObject'
    ///note: protocol requires nested type 'ObserverValue'; do you want to add it?

    associatedtype ObserverValue: Any

    var observers: [ObserverValue] {get set}
}

protocol StringObserver: class {
    func showString()
}

class StringManager: ObserversHolder {
    typealias ObserverValue = StringObserver

    var observers = [ObserverValue]()
}