【问题标题】:Type '[T]' (array Type) does not conform to protocol类型“[T]”(数组类型)不符合协议
【发布时间】:2017-07-14 12:34:52
【问题描述】:

让我用例子来解释这个问题。

我有两个协议名为 - Mappable(在 Git 上可用)和 Responsable(我创建了符合 Mappable 协议的协议)

protocol Responsable: Mappable {
  static func getResponse(map: Map) -> Self
}

方法 1 然后我有 struct 'NSIResponse' 它是通用的并且符合 Mappable 和通用 T 是 Resposable 类型

struct NSIResponse<T>: Mappable where T: Responsable {
mutating func mapping(map: Map) {
    response = T.getResponse(map: map)
  }
}

之后,我创建了符合 Responsable 协议的用户对象结构。

struct User: Responsable {

  var id: Int ?
  mutating func mapping(map: Map) {
      id <- map["id"]
    }
  static func getResponse(map: Map) -> User {
    guard let response = Mapper <User>().map(JSONObject: map["response"].currentValue)
    else {
      return User()
    }
    return response
  }
}

方法 2 好吧,我创建了 getResponse 或 Responsable 因为我不想在 NSIResponse 的映射方法中使用更多行,如下所示

 mutating func mapping(map: Map) {
   switch T.self {
    case is  User.Type: response = Mapper<User>().map(JSONObject: map["response"].currentValue) as? T
    case is Array<User>.Type: response = Mapper<User>().mapArray(JSONObject: map["response"].currentValue) as? T
    default: response <- map["response"]
    }
  } 

我不想使用以前的方法,因为如果我这样做了,那么我必须为每个类编写每两行代码。结果,函数长度会增加。因此,我创建了 T.getResponse(map: map) 方法。

现在我面临的问题

let jsonResponse = response.result.value as? [String: AnyObject]
let nsiResponse = NSIResponse<User>(JSON: jsonResponse) // WORKING
let nsiResponse1 = NSIResponse<[User]>(JSON: jsonResponse) // NOT WORKING and getting Type '[User]' does not conform to protocol Responsable

但是,在方法 2 的情况下它工作正常。 如果您能帮助我解决方法 1,我将不胜感激。

我希望你能理解我的问题。

【问题讨论】:

    标签: ios iphone swift generics swift3


    【解决方案1】:

    这个错误的原因是因为类型Array不符合Responsable,只有User符合。在方法 2 中,您涵盖了这种情况,因此它可以工作。

    你要做的就是扩展Array类型,让它符合Responsable

    extension Array: Responsable {
        mutating func mapping(map: Map) {
          // Logic
        }
    
        static func getResponse(map: Map) -> User {
          // Logic
        }
    }
    

    【讨论】:

    • 嗯,首先,感谢您的回复。从技术上讲你是对的,但在我的情况下它不起作用我想要与 Generic T 做一些事情,以便 T 也可以采用对象数组。
    • @PraviJay 您可以像这样指定数组包含的类型:extension Array where Element == User。这使得元素必须是User 类型。这样做是你想要的吗?
    • 我尝试了扩展 Array where Element == User... 在 NSIResponse 行中仍然出现同样的错误。
    • @PraviJay 刚刚想到。你能做extension Array where Element == Responsable {},然后在数组元素上运行函数吗?如果这不起作用,我什么都想不出来。
    • 我不确定,但我猜 Swift4.0 中添加了条件一致性...我还没有下载 Swift4.0,但如果你使用的是 Swift4,我想你可以使用这样的东西:extension Array: Responsable where Element: Responsable {}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    相关资源
    最近更新 更多