【问题标题】:how can I pass an object to a function which should confirm two protcols in swift?如何将对象传递给应该快速确认两个协议的函数?
【发布时间】:2019-09-04 16:36:08
【问题描述】:

我应该能够传递我为之创建的对象,例如:

Struct Response: Codable {

}

struct Obj: ProtocolB, ProtocolC {

let value: String
let name: String
let num: Int
}
self.request(obj: Obj.self, responseType: Response.self) // This i am able to do.

let ob = Obj(value:"hello",name:"alex",num:1)
self.request(obj: Obj.self, responseType: ob) // This I am not able to do

请建议我如何编写一个接受对象的函数,该对象确认协议 A 和 B 并接受该对象。

func request<T: ProtcolA, X: ProtocolB & ProtocolC>(obj: X, responseType: T.Type) -> Promise<T> {
    let object = X.init() // This is not required but I am doing I should be able to use object directly.
}

【问题讨论】:

  • 你能很好地格式化你的代码吗?真是一团糟
  • 您已经切换了要传递给参数responseTypeobj 的参数。

标签: ios swift generics


【解决方案1】:

我不知道我是否正确地回答了你的问题,但是有你的方法:

func request<T: ProtcolA, X: ProtocolB & ProtocolC>(obj: X, responseType: T.Type) -> Promise<T> {
    let object = X.init() // This is not required but I am doing I should be able to use object directly.
}
  1. T 和 X 是带有约束的泛型类型,而不是参数。这意味着在方法中您必须使用 objresponseType
  2. obj 是一个object(符合ProtcolA),responseType是一个type,所以你不能实例化它
  3. obj在函数内部可以正常使用(let name = obj.name)

但我想问你:为什么需要两个泛型类型?提供更多有关您正在尝试做的事情的信息会更容易

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多