Recently I came across a new way to unwrap optional via the Nil-Coalescing Operator and I found a use case of it during writing some code related to URLSession and URLRequest. The line of interest is line 04:
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "PATCH"
var headers = urlRequest.allHTTPHeaderFields ?? [:]
headers["Content-Type"] = "application/json"So from reading the Swift guide, I have a good idea of what this operator is doing in the context of line04...
1. Either it will unwrap urlRequest.allHTTPHeaderFields if it contains a value
2. Returns [ : ] if urlRequest.allHTTPHeaderFields is nil
3. [ : ] must match the type that is stored inside urlRequest.allHTTPHeaderFields
Since urlRequest.allHTTPHeaderFields is of type [String:String], I am assuming that by entering [ : ] Swift inferred this dictionary to be of type [String:String] otherwise we would have to write this as the code below. I am also assuming that writing it both ways is acceptable?
var headers = urlRequest.allHTTPHeaderFields ?? [String:String]Thanks!