Sch*_*999 5 generics swift option-type
我有一个函数如下:
func request<D: Decodable>(from urlString: String,
useToken: Bool = false,
requestType: RequestType = .get,
body: Data? = nil,
expecting type: D.Type? = nil,
completion: @escaping (Result<D?>) -> Void)
Run Code Online (Sandbox Code Playgroud)
是否可以这样做:request(..., expecting: nil)或func request<D: Decodable>(... expecting type: D.Type? = nil)?
我认为我已经达到了如何使用泛型的限制,因为当我这样做时,我得到的编译错误与我正在处理的代码完全无关,所以我认为编译器可能会感到困惑。
当我使用该函数时,例如:request(from: "https:..", requestType: .post, body: body),编译器抱怨说Enum element 'post' cannot be referenced as an instance member
我的一些 API 请求不会在正文中返回任何内容,因此我试图找到一种方法来使用我设置的通用函数来表达这一点
这对我来说在操场上效果很好
let t = testStruct.init()
let t2 : testStruct? = nil
test(t)
testOptional(t)
testOptional(t2)
func test<T: testProtocol>(_ para: T){
print(para.id())
}
func testOptional<T: testProtocol>(_ para: T?){
if let p = para{
print(p.id())
}
}
protocol testProtocol {
func id() -> String
}
struct testStruct{
}
extension testStruct : testProtocol {
func id() -> String {
return "hello"
}
}
Run Code Online (Sandbox Code Playgroud)
但你不能只调用 testOptional()。它必须传递一些东西,甚至是一个 nil 可选参数,这样才能推断出类型。