Swift:在协议扩展中提供默认协议实现 [英] Swift: Providing a default protocol implementation in a protocol extension

查看:125
本文介绍了Swift:在协议扩展中提供默认协议实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Swift、协议和协议扩展.具体来说,我试图在协议扩展中提供协议的默认实现.这是我的代码:

I'm trying to play around a bit with Swift, protocols and protocol extensions. Specifically I'm trying to provide a default implementation of a protocol in a protocol extension. This is my code:

protocol Proto : class {
    func someMethod() -> String
}

extension Proto {
    static func create() -> Self {
        return ProtoDefaultImpl() as! Self
    }
}

class ProtoDefaultImpl : Proto {
    func someMethod() -> String {
        return "doing something"
    }
}

let instance = Proto.create()
let output = instance.someMethod()

print(output)

编译器在我调用 Proto.create() 的那一行抱怨,并出现以下错误:错误:static member 'create' cannot be used on instance of type 'Proto.协议'.

The compiler complains on the line where I call Proto.create(), with the following error: error: static member 'create' cannot be used on instance of type 'Proto.Protocol'.

我在这里错过了什么吗?有什么办法可以做到这一点吗?

Have I missed something here? Is there any way you can achieve this?

谢谢.

推荐答案

你不能在协议本身上调用方法,你必须在实现协议的类型上调用它.这不会改变,因为扩展中有协议的默认实现.将您的类型从 Proto 更改为 ProtoDefaultImpl,它将按您的预期工作.

You can't call the method on the protocol itself, you have to call it on a type that implements the protocol. This doesn't change because there is a default implementation of the protocol in an extension. Change your type from Proto to ProtoDefaultImpl and it will work as you expect.

protocol Proto : class {
    func someMethod() -> String
}

extension Proto {
    static func create() -> Self {
        return ProtoDefaultImpl() as! Self
    }
}

class ProtoDefaultImpl : Proto {
    func someMethod() -> String {
        return "doing something"
    }
}

let instance = ProtoDefaultImpl.create()
let output = instance.someMethod()

print(output)

输出:doing something

这篇关于Swift:在协议扩展中提供默认协议实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆