类型“[T]”(数组类型)不符合协议

Pra*_*ana 2 generics iphone ios swift swift3

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

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

protocol Responsable: Mappable {
  static func getResponse(map: Map) -> Self
}
Run Code Online (Sandbox Code Playgroud)

方法 1 然后我有结构“NSIResponse”,它是通用的并且符合 Mappable 和通用 T 是 Resposable 类型

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

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

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
  }
}
Run Code Online (Sandbox Code Playgroud)

方法 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"]
    }
  } 
Run Code Online (Sandbox Code Playgroud)

我不想使用以前的方法,因为如果我这样做,那么我必须为每个类编写每两行代码。结果,函数长度会增加。因此,我创建了 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
Run Code Online (Sandbox Code Playgroud)

然而,在方法 2 的情况下它工作得很好。如果您能帮助我解决方法 1,我将不胜感激。

我希望你明白我的问题。

Cal*_*ter 5

出现这个错误的原因是因为类型Array不符合Responsable,只User符合。在方法 2 中,您涵盖了该案例,因此它有效。

您要做的就是扩展类型Array,使其符合Responsable

extension Array: Responsable {
    mutating func mapping(map: Map) {
      // Logic
    }

    static func getResponse(map: Map) -> User {
      // Logic
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不确定,但我猜条件一致性是在 Swift4.0 中添加的...我还没有下载 Swift4.0,但如果你使用 Swift4,我想你可以使用这样的东西: `extension Array :负责,其中元素:负责{}` (2认同)