Swift's Nil Coalescing Operator Example

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!

Accepted Reply

Nearly true


you have to write


var headers = urlRequest.allHTTPHeaderFields ?? [String:String]()

Here you use the type definition. To initiate an empty dictionary you must use the init : ()


But you can write


var headers = urlRequest.allHTTPHeaderFields ?? [:]

As type is inferred, you can use the empty dictionary directly


Look here for more details

h ttps://dmitripavlutin.com/concise-initialization-of-collections-in-swift/

Or directly in Swift Programming language (about page 21)

Replies

Nearly true


you have to write


var headers = urlRequest.allHTTPHeaderFields ?? [String:String]()

Here you use the type definition. To initiate an empty dictionary you must use the init : ()


But you can write


var headers = urlRequest.allHTTPHeaderFields ?? [:]

As type is inferred, you can use the empty dictionary directly


Look here for more details

h ttps://dmitripavlutin.com/concise-initialization-of-collections-in-swift/

Or directly in Swift Programming language (about page 21)

Awesome. Thank you!