Swift 协议定义类方法返回自我 [英] Swift protocol defining class method returning self

查看:90
本文介绍了Swift 协议定义类方法返回自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码可以在 XCode 6 beta 中运行,但最近在更新到 xcode 6.1 后停止运行.

I had code that was working in XCode 6 beta but stopped working recently after updating to xcode 6.1.

这是我的协议:

protocol CanDeserialiseFromJson {
    class func FromJson(json : JSONValue) -> Self
}

这是实现:

extension Invoice : CanDeserialiseFromJson {
    class func FromJson(json : JSONValue) -> Self {
        return Invoice()
    }
}

这失败给出错误:

'Invoice' is not convertable to 'Self'

正如我所说,这曾经有效,但我不知道为什么它不再有效

As I said, this used to work and I can't work out why it doesn't anymore

推荐答案

Self 在协议中是要求协议的实现使用自己的类型.由于 Invoice 是您采用协议的类型,您的 FromJson 实现应该具有 Invoice 的返回类型.

Self in a protocol is a requirement that implementations of the protocol use their own type. Since Invoice is the type you're adopting the protocol in, your implementation of FromJson should have a return type of Invoice.

这篇关于Swift 协议定义类方法返回自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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