带有可选泛型参数的Swift函数

xbp102n0  于 2023-06-28  发布在  Swift
关注(0)|答案(1)|浏览(151)

我试图创建一个通用的URLRequest创建函数,但我的实现在没有主体时给我一个错误。我该怎么解决这个问题?

guard let request: URLRequest = RequestMaker.requestMaker(url: followUser, method: .get) else { return false }

给出此错误:Generic parameter 'T' could not be inferred

class RequestMaker {
    static func makeRequest<T: Encodable>(
        url: String,
        method: HTTPMethod,
        _ body: T? = nil
    ) -> URLRequest? {
        guard let url: URL = .init(string: url) else { return nil }
        var request: URLRequest = .init(url: url)
        request.httpMethod = method.rawValue
        request.addAuthorizationHeader()
        request.timeoutInterval = 15.0
                
        if let body: T = body {
            request.httpBody = try? JSONEncoder().encode(body)
        }
        
        return request
    }
}
lsmepo6l

lsmepo6l1#

我认为最方便的方法是创建另一个非泛型重载,并使body在原始重载中不是可选的。
在新重载中调用泛型重载,这样就不会重复代码,并将nil传递给body,但首先将其强制转换为特定的Encodable类型,以便可以推断T

static func makeRequest(
    url: String,
    method: HTTPMethod
) -> URLRequest? {
    // here I used String, but any Encodable type would work
    makeRequest(url: url, method: method, nil as String?)
}

相关问题