Teaching myself Swift, and looking at this answer here.
The part that's confusing me the most is this bit:
let task = URLSession.shared.dataTask(with: request) { data,
response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data,
options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
I'll walk through the parts I do understand, and I'm hoping someone can help me fill in the gaps.
- The
let task = ...
part is assigning a newURLSessionDataTask
object to the variabletask
with the passed inrequest
data. I get that. data
,response
, anderror
(followed byin
) seem to be placeholder parameters. Is this correct? And does thein
keyword signify that these are input parameters? I read on Apple's documentation that they can bein-out
parameters, so I'm thinking that's what this means. This mini-function of sorts accepts, rather than returns, something.guard let data = ...
this is a weird concept coming from other languages. From what I understand, theguard
statement defines a set ofBool
/boolean expressions, all of which have to be true, else the code inside the block is executed. So basically, ifdata
cannot receive anything, and iferror
isnil
/null
, print an error message and return.- If all else is successful, print the JSON response and finish.
I guess the most foreign concept to me is the let ... _, _, _ in
statement, since the syntax just looks really weird (placeholder parameters come after the opening {
?)
I tried searching for documentation on this type of statement, and Apple compared it to a lambda expression in other languages. I can sort of see that with the data, response, error
part.
So, if anyone can help clear a couple things up about this, it'd be much appreciated. Thanks!