【问题标题】:SWIFT - How to compare instance of an array typed with ProtocolSWIFT - 如何比较使用协议类型的数组实例
【发布时间】:2015-05-11 08:24:28
【问题描述】:

我是 Swift 代码的新手,很抱歉我的英语不好。 这是我的代码:

var t = Array<MyClassProtocol> ()
var instance1 = MyClasse () //protocol MyClassProtocol
var instance2 = MyClasse () //protocol MyClassProtocol 
var instance3 = MyClasse2 () //protocol MyClassProtocol 
t.append (instance1)
t.append (instance2)
t.append (instance3)

//What I try to do 

for instance in t
{
    if (instance === instance1){ /* do something */ }
}

XCode 返回:类型 MyClassProtocol 不符合协议 “任何对象”

有什么想法吗? 谢谢

【问题讨论】:

  • 我们还能看到 MyClasse 和 MyClasse2 类吗

标签: swift


【解决方案1】:

=== 运算符只能应用于类的实例。然而,Swift 不仅有类,它还有结构。结构体也可以采用MyClassProtocol。问题是当 Swift 只看到instanceMyClassProtocol 时,它不知道它是一个结构还是一个类,所以你不能使用===

要解决它,您需要防止MyClassProtocol 被结构采用。这是通过让它继承自AnyObject(这是一个空的类协议)来完成的。

protocol MyClassProtocol : AnyObject {

【讨论】:

    【解决方案2】:

    你需要让 MyClassProtocol 继承自 AnyObject

    protocol MyClassProtocol : AnyObject {
    
    }
    

    【讨论】:

      【解决方案3】:

      我认为你的 MyclassProtocol 不是从 AnyObject 继承的。 所以试试这个:它可能是有效的。

      protocol MyClassProtocol:AnyObject{ // make sure  you protocol inherit from AnyObject
       func doSomething()
      } 
      
      
      
      
      class Myclass:MyClassProtocol{
       func doSomething() {
      
       }
      }
      
      class Myclass2: MyClassProtocol {
       func doSomething() {
      
       }
      } 
      var t = Array<MyClassProtocol>()
      var instance1 = Myclass () //protocol MyClassProtocol
      var instance2 = Myclass () //protocol MyClassProtocol
      var instance3 = Myclass2 () //protocol MyClassProtocol
      t.append (instance1)
      t.append (instance2)
      t.append (instance3)
      
      
      for instance in t{
        if (instance === instance1){
      
       }
      }
      

      【讨论】:

      • 它有效!十分感谢。知道了就简单了!
      【解决方案4】:

      您的类将需要实现协议 MyClassProtocol

      例如

      class MyClasse: NSObject, MyClassProtocol
                                ^ Here we tell the class that it should implement the protocol
      

      顺便说一句,你也可以像这样声明你的数组:

      var t : [MyClassProtocol] = [];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-14
        • 2016-09-22
        • 1970-01-01
        • 2017-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多