I'm using this extension in order to retrieve HTTP headers within a urlSession callback:
extension HTTPURLResponse {
func get(_ header: String) -> String? {
let keyValues = allHeaderFields.map { (String(describing: $0.key).lowercased(), String(describing: $0.value)) }
if let headerValue = keyValues.filter({ $0.0 == header.lowercased() }).first {
return headerValue.1
}
return nil
}
}
This works well and allows me to retrieve header elements like so:
if let metaInt = httpResponse.get("icy-metaint") {
self.icyMetaInt = Int(metaInt)
}
Now I wanted it to make a little bit more elegant by introducing a generic function:
func getHeader<T>(_ httpResponse: HTTPURLResponse, _ headerName: String) -> T? {
guard let element = httpResponse.get(headerName) else {
return nil
}
return T(element)
}
The intention is to use statements like this:
self.icyMetaInt = getHeader(httpResponse, "icy-metaint")
I believe something like that would work in C# or so. But the Swift compiler complains:
Non-nominal type 'T' does not support explicit initialization
for
return T(element)
Even though if I use
return T.init(element)
Is there any chance to achieve what I'm having in mind?
EDIT: Added T? (must have been lost while editing)