logoalt Hacker News

scottmflast Tuesday at 2:56 PM4 repliesview on HN

Concurrency issues aside, I've been working on a greenfield iOS project recently and I've really been enjoying much of Swift's syntax.

I’ve also been experimenting with Go on a separate project and keep running into the opposite feeling — a lot of relatively common code (fetching/decoding) seems to look so visually messy.

E.g., I find this Swift example from the article to be very clean:

    func fetchUser(id: Int) async throws -> User {
        let url = URL(string: "https://api.example.com/users/\(id)")!
        let (data, _) = try await URLSession.shared.data(from: url)
        return try JSONDecoder().decode(User.self, from: data)
    }

And in Go (roughly similar semantics)

    func fetchUser(ctx context.Context, client *http.Client, id int) (User, error) {
        req, err := http.NewRequestWithContext(
            ctx,
            http.MethodGet,
            fmt.Sprintf("https://api.example.com/users/%d", id),
            nil,
        )
        if err != nil {
            return User{}, err
        }
    
        resp, err := client.Do(req)
        if err != nil {
            return User{}, err
        }
        defer resp.Body.Close()
    
        var u User
        if err := json.NewDecoder(resp.Body).Decode(&u); err != nil {
            return User{}, err
        }
        return u, nil
    }

I understand why it's more verbose (a lot of things are more explicit by design), but it's still hard not to prefer the cleaner Swift example. The success path is just three straightforward lines in Swift. While the verbosity of Go effectively buries the key steps in the surrounding boilerplate.

This isn't to pick on Go or say Swift is a better language in practice — and certainly not in the same domains — but I do wish there were a strongly typed, compiled language with the maturity/performance of e.g. Go/Rust and a syntax a bit closer to Swift (or at least closer to how Swift feels in simple demos, or the honeymoon phase)


Replies

tarentellast Tuesday at 5:04 PM

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.
show 4 replies
tidwalllast Tuesday at 3:16 PM

Or this.

    func fetchUser(id int) (user User, err error) {
        resp, err := http.Get(fmt.Sprintf("https://api.example.com/users/%d", id))
        if err != nil {
            return user, err
        }
        defer resp.Body.Close()
        return user, json.NewDecoder(resp.Body).Decode(&user)
    }
show 1 reply
neonsunsetlast Tuesday at 3:58 PM

C# :)

    async Task<User> FetchUser(int id, HttpClient http, CancellationToken token)
    {
        var addr = $"https://api.example.com/users/{id}";
        var user = await http.GetFromJsonAsync<User>(addr, token);
        return user ?? throw new Exception("User not found");
    }
hocuspocuslast Tuesday at 3:34 PM

Not defending Go's braindead error handling, but you'll note that Swift is doubly coloring the function here (async throws).

show 2 replies