热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Swift协议定义返回self的类方法-Swiftprotocoldefiningclassmethodreturningself

IhadcodethatwasworkinginXCode6betabutstoppedworkingrecentlyafterupdatingtoxcode6.1

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

我的代码在XCode 6测试版中有效,但在更新到xcode 6.1后最近停止了工作。

This is my protocol:

这是我的协议:

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

This is implementation:

这是实施:

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

This fails giving error:

这没有给出错误:

'Invoice' is not convertable to 'Self'

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

正如我所说,这曾经工作,我无法解决为什么它不再

2 个解决方案

#1


2  

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.

协议中的Self要求协议的实现使用它们自己的类型。由于Invoice是您采用协议的类型,因此FromJson的实现应具有Invoice的返回类型。

#2


4  

It's right. Your method is declared to return Self, whereas you are returning Invoice. Class methods are inherited, and in subclasses, Self will be that subclass type, and Invoice is not a subtype of that type.

这是正确的。声明您的方法返回Self,而您返回Invoice。类方法是继承的,在子类中,Self将是该子类类型,而Invoice不是该类型的子类型。

To actually return Self, assuming Invoice has a required init() constructor, you can do something like this:

要实际返回Self,假设Invoice具有必需的init()构造函数,您可以执行以下操作:

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

推荐阅读
author-avatar
加勒比海盗的骷髅_829
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有