gpt4 book ai didi

swift - 如何在 Swift 中为协议(protocol)指定一致的类

转载 作者:搜寻专家 更新时间:2023-11-01 06:31:52 25 4
gpt4 key购买 nike

我想知道是否可以创建一个协议(protocol),其中它的方法引用符合类的类型

UHSyncObjectProtocol 协议(protocol)

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)
}
}

我不确定这是否可能。

最佳答案

你可以使用泛型来实现这一点

这里是例子

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)
}
}

关于swift - 如何在 Swift 中为协议(protocol)指定一致的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46211019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com