如何在Swift中为协议指定一致的类

时间:2017-09-14 05:15:14

标签: swift

我想知道是否可以创建一个协议,其方法引用一致类的类型

UHSyncObjectProtocol协议

protocol UHSyncObjectProtocol: class {
     func sync(completionBlock: ((UHSyncObjectProtocol) -> Void)?)
     // ideally, I want to refer to the conforming class instead of UHSyncObjectProtocol
} 

用户个人资料类

class UHUserProfile: UHSyncObjectProtocol {
     func sync(completionBlock: ((UHUserProfile) -> Void)?) {
        // do something
        completionBlock?(self)
     }
}

用户帐户类

class UHUserAccount: UHSyncObjectProtocol {
     func sync(completionBlock: ((UHUserAccount) -> Void)?) {
        // do something
        completionBlock?(self)
     }
}

我不确定是否可能。

1 个答案:

答案 0 :(得分:3)

您可以使用泛型来实现

这是示例

protocol UHSyncObjectProtocol: class {
    associatedtype T

    func sync(completionBlock: ((T) -> Void)?)
    // ideally, I want to refer to the conforming class instead of UHSyncObjectProtocol
}

class UHUserProfile: UHSyncObjectProtocol {
    func sync(completionBlock: ((UHUserProfile) -> Void)?) {
        // do something
        completionBlock?(self)
    }
}

class UHUserAccount: UHSyncObjectProtocol {
    func sync(completionBlock: ((UHUserAccount) -> Void)?) {
        // do something
        completionBlock?(self)
    }
}