为什么在 swift 中我们不能在没有从 NSObject 继承类的情况下采用协议? [英] Why in swift we cannot adopt a protocol without inheritance a class from NSObject?

查看:44
本文介绍了为什么在 swift 中我们不能在没有从 NSObject 继承类的情况下采用协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用以下代码,它会显示我的错误类型‘HttpConnection’不符合协议‘NSObjectProtocol’"

class HttpConnection : NSURLConnectionDataDelegate {var urlConnection : NSURLConnection?弱变量委托:HttpConnecting?初始化(委托:HttpConnecting){self.delegate = 委托;}func startAsynRequestWithUrlString(url:NSString, withMethod:NSString){}}

如果我将 HttpConnection 子类化为 NSObject,那么它工作正常.所以我的问题是当我需要快速采用 NSURLConnectionDataDelegate 协议时,为什么我需要从 NSObject 继承类?

解决方案

NSURLConnectionDataDelegate 本身继承自 NSURLConnectionDelegate,后者继承自 NSObjectProtocol.>

这意味着除了实现 NSURLConnectionDataDelegateNSURLConnectionDelegate 中的所有方法外,还必须实现 NSObjectProtocol 中的所有方法(例如相等,哈希).

您没有实施它们,那是您的错误.如果你从 NSObject 继承,所有 NSObjectProtocol 方法都已经为你实现了.

If i use the following code it shows me error "Type 'HttpConnection' does not conform to protocol 'NSObjectProtocol'"

class HttpConnection : NSURLConnectionDataDelegate {
        var urlConnection       : NSURLConnection?
        weak var delegate       : HttpConnecting?

        init(delegate:HttpConnecting){
            self.delegate = delegate;
        }

        func startAsynRequestWithUrlString(url:NSString, withMethod:NSString){
        }
    }

If i subclass HttpConnection to NSObject then it works fine. So my question is when i need to adopt NSURLConnectionDataDelegate protocol in swift why i need to inherit the class from NSObject?

解决方案

NSURLConnectionDataDelegate itself inherits from NSURLConnectionDelegate which inherits from NSObjectProtocol.

That means that apart from implementing all the methods from NSURLConnectionDataDelegate, and NSURLConnectionDelegate, you also have to implement all the methods from NSObjectProtocol (e.g. equality, hash).

You didn't implement them, that's your mistake. If you inherit from NSObject, all that NSObjectProtocol methods are already implemented for you.

这篇关于为什么在 swift 中我们不能在没有从 NSObject 继承类的情况下采用协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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