by tarentel · 11mo ago · 0 comments
The first line won't crash but in practice it is fairly rare where you'd implicitly unwrap something like that. URLs might be the only case where it is somewhat safe. But a more fair example would be something like
func fetchUser(id: Int) async throws -> User {
guard let url = URL(string: "https://api.example.com/users/\(id)") else {
throw MyError.invalidURL
}
// you'll pretty much never see data(url: ...) in real life
let request = URLRequest(url: url)
// configure request
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
200..<300 ~= httpResponse.statusCode else {
throw MyError.invalidResponseCode
}
// possibly other things you'd want to check
return try JSONDecoder().decode(User.self, from: data)
}
I don't code in Go so I don't know how production ready that code is. What I posted has a lot of issues with it as well but it is much closer to what would need to be done as a start. The Swift example is hiding a lot of the error checking that Go forces you to do to some extent.Still better than the 3 lines of if err is not nil that go gets you to do though.
let request = URLRequest(url: url)
let (data, response) = try await URLSession.shared.data(for: request)
// vs
let (data, response) = try await URLSession.shared.data(from: url)
That aside, your Swift version is still about half the size of the Go version with similar levels of error handling.The second one is for downloading directly from a URL and I've never seen it used outside of examples in blog posts on the internet.
I think the point of the comment was that in many cases, when constructing a url, you can't be sure that the input will result in a valid url (e.g. when receiving a string instead of an int), so you have to be more defensive and the required code is more verbose.
let x: Int? = 0
let y: Int = x!
git ls-files -z -- '*.swift' | xargs -0 swift format lint --parallel
error: [NeverForceUnwrap] do not force unwrap 'x'