ios - 我可以使用基于返回值的设置占位符类型吗?

标签 ios swift generics protocols swift-protocols

我想在协议(protocol)中指定一个函数,其返回值与当前实现类的类型相匹配。

protocol MakesSelf {
    static func getInstance<T>() -> T
}

除非 T 被限制为与实现 MakesSelf 的人相同的类型,例如

class MyThing: MakesSelf {

    class func getInstance<T>() -> T {
        return MyThing()
    }

}

我的理解是,编译器会根据返回值为 T 分配 MyThing 的类型,但我得到的是类型转换错误:无法转换 ' 类型的返回表达式MyThing' 返回类型 'T'

最佳答案

您可以创建一个具有关联类型的协议(protocol),您的 getInstance() 函数将返回该类型。在协议(protocol)的扩展中创建该功能的默认实现。完整示例:

protocol Initializable {
    init()
}

protocol MakesSelf: Initializable {
    associatedtype Object: Initializable = Self
    static func getInstance() -> Object
}

extension MakesSelf {
    static func getInstance() -> Object {
        return Object()
    }
}

class MyThing: MakesSelf {
    required init() {}

    func printSelf() {
        print(MyThing.self)
        print(Object.self)
        // Both will print "MyThing" because Object is a typealias of MyThing class
    }
}

然后获取您的实例:

let instance = MyThing.getInstance()
print("\(instance.self)")
/* Will print: MyTestApp.MyThing */

如您所见,因为您已经在协议(protocol)的扩展中给出了 getInstance() 的默认实现,这在符合类中不是必需的。在您的问题的上下文中,关联类型用作“占位符”。

关于ios - 我可以使用基于返回值的设置占位符类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50254617/

相关文章:

c# 通过 WCF 将 arraylist 从客户端传递到服务器端

java泛型数组和ClasscastException

iphone - UITableView 在 Forground 状态下 Enter 后不重新加载数据

ios - 升级Xcode问题

ios - NSTimer 要求我将其添加到运行循环中

ios - 使用最新的 Xcode 和 iOS 11 启动屏幕编辑在我的任何 iPhone 应用程序上都不起作用

Swift - 前一周的开始日和结束日

javascript - 如何从我的 html 文件移动到另一个 html 文件以创建 iOS 混合应用程序?

ios - Coredata 链接关系

java - 动态类型方法中的奇数类型推断