September 6th, 2024

Swift is a more convenient Rust

Swift and Rust are both functional programming languages with LLVM-based compilers, but Rust focuses on performance and memory management, while Swift emphasizes ease of use and developer productivity.

Read original articleLink Icon
DisagreementAppreciationSkepticism
Swift is a more convenient Rust

The article discusses the similarities and differences between Swift and Rust, two programming languages that share many features but cater to different programming paradigms. Both languages incorporate functional programming concepts such as tagged enums, match expressions, and first-class functions, and they utilize an LLVM-based compiler for native code and WebAssembly (WASM) compilation. However, Rust is characterized as a low-level systems language that emphasizes performance and memory management through ownership, while Swift is a high-level language designed for ease of use and developer productivity. Swift employs a default value-type memory model with copy-on-write semantics, making it simpler to use, whereas Rust requires more explicit handling of memory through its ownership system. The article highlights that Swift's syntax is designed to be familiar to developers coming from C-like languages, often hiding complex concepts behind simpler constructs. While Rust's compiler enforces strict rules to catch potential issues at compile time, Swift offers a more automatic approach, which can lead to less explicit handling of certain programming challenges. Ultimately, the author concludes that Rust is better suited for systems programming, while Swift excels in UI development and server-side applications, with an expectation of increasing overlap between the two languages in the future.

- Swift and Rust share many functional programming features but differ in their approach to memory management.

- Rust is a low-level language focused on performance, while Swift prioritizes ease of use and developer productivity.

- Swift's syntax is designed to be familiar to C-like language developers, often simplifying complex concepts.

- Rust's compiler enforces strict rules, while Swift's compiler offers a more automatic handling of programming challenges.

- Rust is ideal for systems programming, whereas Swift is better for UI and server-side applications.

AI: What people are saying
The discussion around Swift and Rust highlights several key themes and opinions from the comments.
  • Rust is praised for its performance and memory management, particularly its ownership model, while Swift is noted for its ease of use and developer productivity.
  • Many commenters express frustration with Swift's limitations outside the Apple ecosystem, suggesting it is primarily an Apple-centric language.
  • There is a consensus that Rust has a more robust package ecosystem compared to Swift, which struggles with cross-platform compatibility.
  • Some users find Rust's syntax complex and challenging, while others appreciate Swift's more straightforward syntax.
  • Tooling and developer experience are significant points of contention, with Rust being favored for its superior tooling compared to Swift's limitations on non-Mac platforms.
Link Icon 30 comments
By @noelwelsh - 4 months
Hmmm...I disagree with a number of statements in the post but I think the following two hypotheses will make for more interesting discussion than some nitpicks:

1. A large part of why many people love Rust is that it's the first time they've used an ML family language. One of the innovations of Rust was to create a community that felt like home to Unix hackers who weren't programming language nerds.

2. Rust is the first language to bring non-GC automatic memory management to the mainstream. It won't be the last and it might well be the worst. Other languages in this space include Swift (as in OP's post), OCaml[1], and Scala[2]. These alternatives take the approach that tracking ownership is not the default, which is fine for the majority of programs and far more ergonomic.

There's also a corollary

3. The age of Smalltalk is over. It's now the age of ML. (Amusingly, going backwards in time, from 1983 to 1975). The languages that dominated the 2000s (Ruby, Python, Javscript, PHP) were all more or less derived from Smalltalk (everything is an object! dynamic types! runtime metaprogramming!) The new languages (Rust, Scala, Swift, Kotlin, etc.) are ML family languages. Similarly, back in the day you could learn, say, Ruby, and still be reasonably proficient in Python or JS. Now you can learn, say, Scala, and pick up Rust or Swift reasonably easily.

[1]: https://blog.janestreet.com/oxidizing-ocaml-locality/

[2]: https://dl.acm.org/doi/full/10.1145/3618003

By @afavour - 4 months
As someone that’s recently been working on integrating Rust into an iOS Swift app I do agree with a lot of this. I love Rust but the more I’ve used Swift the more I find myself wishing I was just using Swift all the time.

That said, the difference between the two has a lot less to do with the language itself than the world surrounding it. You can use Swift cross platform but it’s very obvious that Apple platforms are the primary target. Rust has a rich and varied package system, about the only assumption most packages make is that you’re using the Rust standard library. By comparison lot of Swift packages (which is a much smaller ecosystem anyway that’s slowly transitioning away from Cocapods, Carthage etc) will lean on OS APIs that won’t work if you compile for Linux or WASM[1].

I want Swift to be a more convenient Rust but it just isn’t there. e.g look at IBM abandoning Swift on the server not that long ago.

[1] for example, this blog post:

https://swiftrocks.com/weak-dictionary-values-in-swift

Discusses making a dictionary with weak values in Swift. It has a homegrown Swift version then discusses using NSMapTable… which isn’t available on Linux. But you wouldn’t know that reading the article because the assumption is that you’re running on an Apple platform.

By @nicce - 4 months
> Rust invented the concept of ownership as a solution memory management issues without resorting to something slower like Garbage Collection or Reference Counting.

They did it well, but not invented?

There very many kinds of influeces: https://www.reddit.com/r/rust/comments/le7m54/is_it_fair_to_...

Especially Cyclone, I think: https://en.m.wikipedia.org/wiki/Cyclone_(programming_languag...

By @K0nserv - 4 months
I love both Rust and Swift, they have their respective strengths. I would say Swift has a less noisy surface syntax, but instead uses more dedicated keywords and compiler magic. This is nicer, but means some areas are "compiler only territory".

In many cases Swift would be a better choice than Rust, when the convenience and developer experience is worth trading for some performance. However, Swift's biggest problem is that any usage outside of the Apple ecosystem is a second(or third) class citizen. Until this is solved, Swift will remain mostly an Apple only language, regardless of how nice it is.

By @robjwells - 4 months
One way that Swift is certainly not more convenient than Rust is the tooling. I use a 2018 MacBook Air, using macOS 12, which is now unsupported by Xcode. Meanwhile SourceKit-LSP is treated as very much a second-class citizen. But Rust 1.81 and rust-analyzer build and run just fine.
By @seanalltogether - 4 months
I keep trying to get into rust but I always hit a brick wall when looking at examples and the code looks so complicated. Examples like this straight from the rust website just make my eyes glaze over

    struct Task {

        future: Mutex<Option<BoxFuture<'static, ()>>>,

        task_sender: SyncSender<Arc<Task>>,
    }
By @agubelu - 4 months
> In fact, Swift treats enums as more than just types and lets you put methods directly on it

You can do the exact same thing in Rust:

  impl Coin {
      fn valueInCents(&self) -> u8 {
          match self {
              Self::Penny => 1,
              Self::Nickel => 5,
              Self::Dime => 10,
              Self::Quarter => 25,
          }
      }
  }
By @SneakerXZ - 4 months
> Swift use value-types by default with copy-on-write semantics.

This isn't true. Copy-on-write semantics are implemented only for arrays, dictionaries, and strings. Swift value-types are copied immediately.

https://docs.swift.org/swift-book/documentation/the-swift-pr...

By @mogoh - 4 months
Always, when I read those postings that praise Swift, I wonder how good is the developer experience is if you don't use any of the Apple/MacOS ecosystem (except Swift, of course). I have not met any Swift developer who is not developing on macOS, usually for macOS. That makes me very skeptical that non-Mac devs are treated as second-class citizens. I am not only talking about the standard library, but also about the tooling, LSP, libraries, tutorials and so on. I totally believe that Swift is a good language, but I guess it is only good if you are on macOS.

If you are developing with Swift but not using a Mac at all, I would love to hear how your experience has been.

By @lukeh - 4 months
I don’t know Rust, but I’m loving Swift for systems programming. Most recent project was an 802.1Q SRP implementation and I couldn’t imagine going back to C. Higher up the stack, I’ve also used it with a custom runner to build the business logic for an embedded Flutter app.

My only beef is that the binaries are quite large. I’m hoping the new Foundation will improve things, in the interim I’m trying to eliminate my Foundation dependencies.

By @hardwaresofton - 4 months
Am I the only one that dislikes the dot syntax for variants?

Zig and Swift do it and I feel like it makes things harder to read, not easier.

`.variant` vs `Type::Variant`

IIRC the syntax is optional (you can include the type name) but it seems obvious that in any sufficiently long or complex code, not having the type name close would be annoying, especially if you didn’t have IDE like capabilities in your editor.

By @pjmlp - 4 months
What Rust did great was bringing affine type systems into mainstream culture.

However outside very specific use cases, where no kind of automatic resource management is allowed, no matter what, like in high integrity computing, or critical kernel code, approaches that mix and match both solutions are much more ergonomic.

Swift isn't the only one going down this route, we see it as well in D, Chapel, Linear Haskell, OCamml Effects, Mojo, Hylo, Koka, Veronica, and probably many other research languages being born during the last 5 years.

Because in the end, programming language ergonomics and expressiveness really matters for wide scale adoption.

By @rich_sasha - 4 months
My interest in Rust stems from a very good Python interop. There's a very small handful of compiled languages with that property: Rust, C++, Nim (which is itself quite niche)... That's basically it as far as I know. Swift doesn't seem to tick that box.

I would happily have something 50-100% slower than C++/Rust with good interop, alas there seems to be very little / nothing. Cython for various reasons isn't ideal.

By @prmoustache - 4 months
Unrelated to the blogpost in question but I don't understand why the author is not using its own certificate if he is using his own domain.

Using an browser set to autodirect to https by default, all I get is some huge warning because the host use a certificate for svbtle, the service used to host this blog.

I know some people think that because some blogpost is public it can be served without ssl, but I think it is still nice to leave the choice of the reader to disclose or not to his provider and everyone in between what he is reading or not without seeing horrible warnings.

By @lame-lexem - 4 months
Rust's `Vec` already allocate values on the heap, so there is no need for another inderection with `Box`.

this works:

  enum TreeNode<T> {
      Leaf(T),
      Branch(Vec<TreeNode<T>>),
  }
https://play.rust-lang.org/?version=stable&mode=debug&editio...

otherwise if it was just tuple of `TreeNode` there would be E0072 https://doc.rust-lang.org/stable/error_codes/E0072.html

By @tromp - 4 months
> it gives you utilities such as Rc, Arc and Cow to do reference counting and “clone-on-right”

Not quite right:

[1] https://en.wikipedia.org/wiki/Copy-on-write

By @__jonas - 4 months
Does Swift make it as easy as Go or Rust to produce a single binary for any target platform? Would it be a good choice for a CLI application?

It sounds kind of intriguing but I know very little about the language.

By @BiteCode_dev - 4 months
Swift won't be able to compete with rust until it has a great scripting story.

Rust is currently the defactor choice if you want to make something with js/python bindings, of id you want to speed up a dynamic bottleneck because it makes it super easy.

Swift doesn't even have a good ffi.

By @dist1ll - 4 months
The tree example is quite contrived. Most Rust programmers would use indices for indirection, pointing into flat buffers.
By @high_priest - 4 months
Yes! And C# is just more convenient C.
By @StewardMcOy - 4 months
As someone who has worked on large projects in both Swift and Rust, I have to disagree with the author about error handling. It's not perfect, but Rust's use of Result and syntactic sugar is probably the best solution to error handling I've ever used. try/catch (or in Swift's case do/catch) is more disruptive to the program flow. And prior to Swift 6, throws in Swift were untyped.

(Yes, there's arguments that untyped throws are better for library code because it leaves you more room to add more errors as you become aware of the need for them without breaking the contract with your users, but really, client code is going to be written to the errors you're throwing anyway (i.e. Hyrum's Law). I much prefer my errors to be typed so that if an error is added, the library version has to be bumped to indicate the new incompatibility with old code. And for my own, non-library code, typed errors make sure I'm handling all the error cases.)

By @singularity2001 - 4 months
'Swift is the better rust' inspired by the why-ruby-is-an-acceptable-lisp debate: http://www.randomhacks.net/2005/12/03/why-ruby-is-an-accepta...
By @lostmsu - 4 months
The article is outright wrong at times (like the need for Box or special status of enums), and is missing 80% reason to use Rust: it helps to ensure correctness of multi threaded synchronization at compile time.

So no, Swift is not a "more convenient Rust". It is not Rust at all. It is more of a variant of C#/Java. And I haven't seen any indication that it is an improvement over either. The only reason to use Swift is having to deal with Apple.

By @jb1991 - 4 months
> But when you need extra speed you can opt into an ownership system and “move” values to avoid copying.

I've been using Swift a long time and don't quite get what this is referring to.

Also:

> Swift too gives you complete type-safety without a garbage collector.

Type-safety and memory-safety are two entirely different things; this is an odd sentence.

By @andrewstuart - 4 months
If only it wasn't so heavily tied to Apple.
By @neonsunset - 4 months
And C# is a cross-platform and faster Swift :)
By @tkz1312 - 4 months
I mean basically everything is a more convenient rust...
By @dangoodmanUT - 4 months
Clone-on-write...