|
|
|
|
|
by tarentel
163 days ago
|
|
As someone who has been coding production Swift since 1.0 the Go example is a lot more what Swift in practice will look like. I suppose there are advantages to being able to only show the important parts. 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.