【问题标题】:Data type inside swift protocol [duplicate]swift协议中的数据类型[重复]
【发布时间】:2015-11-30 10:33:46
【问题描述】:

假设我有以下协议:

protocol DataResponse { .... }

我的问题是,我怎样才能制作像下面这样的另一个协议? :

protocol AnotherProtocol { var data:[DataProtocol] { get } }

当我尝试在下面的Struct 中执行上述操作时,我得到Type 'MyStruct' does not conform to protocol 'AnotherProtocol'

struct myStruct : AnotherProtocol {

  var data:[a struct implements DataProtocol] ...
}

【问题讨论】:

    标签: ios swift protocols


    【解决方案1】:

    你想实现什么?

    protocol DataResponse {
    }
    
    protocol AnotherProtocol {
        var data:[DataResponse] { get }
    }
    
    struct myStruct : AnotherProtocol {
        var data:[DataResponse]
    }
    

    此代码编译。

    【讨论】:

      【解决方案2】:

      您的答案中的代码不是很清楚,所以我不知道您要做什么,但这应该适合您:

      protocol DataProtocol {
      }
      
      protocol AnotherProtocol {
          var data:[DataProtocol] { get }
      }
      
      struct dataStruct : DataProtocol {
      }
      
      struct myStruct : AnotherProtocol {
      
          var data:[DataProtocol] {
              return [dataStruct()]
          }
      }
      

      【讨论】:

      • 我想做的是struct myStruct : AnotherProtocol { var data:[dataStruct] { return [dataStruct()] } } ,因为我有很多结构实现DataProtocol
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      相关资源
      最近更新 更多