Does Swift have cost-free abstractions like Rust?

Does Swift have cost-free abstractions like Rust?

Beyond that, what would you say is (are) the major advantage(s) of Rust over Swift?

I’m studying Rust out of sheer curiosity, but I will have to learn Swift as well for iOS and Mac projects.If I dropped Rust ans stuck with Swift, is there an essential feature I would miss?

Some language features are similar, but Rust tends to give programmer more low-level control.

The main difference is that Rust doesn't do any heap allocations or reference counting automatically. Swift does. Swift has many features that look similar to Rust's and may optimize to code equivalent to Rust's, but that's not a guarantee.

If you write code that happens to hit slow paths in Swift (and automatically allocate and refcount where it shouldn't), it can be even slower than JavaScript:

1 Like

Forget about performance, there are way more interesting differences between the two languages (usually to the advantage of Rust).

For instance, generics are more powerful in Rust; Swift has trouble expressing some very fundamental kinds of constraints, and const evaluation is nowhere to be found in Swift.

Another important thing that Swift doesn't provide is static thread safety. Although there are ergonomic concurrency APIs (libdispatch), they can still be misused, as thread safety is not part of the type system in Swift.

There's also the question of compile-time metaprogramming and extensibility. Rust provides macros (declarative as well as procedural), while Swift doesn't have such user-facing extensibility. Some built-in protocols have a capability similar to Rust's #[derive] proc-macros, but they are wired into the compiler and have to be RFC'd into the language on a case-by-case basis.

Finally, there's move semantics. Swift, like C++, copies value types (structs, enums, and primitive builtins) automatically, so there's no way to express single ownership reliably. Incidentally, value types containing references are also copied implicitly, so it's even easier to accidentally share ownership of a value.


To provide a counterpoint re: Linux usability, funnily enough, I had more trouble getting Swift to work on macOS than I had on Ubuntu. On macOS, the Swift toolchain does indeed require Xcode. The command line tools is not enough; for some reason, swift build and the Swift package manager does not work unless you install the Xcode GUI proper. (That just blows my mind.) On the other hand, I have had absolutely no trouble using it on Ubuntu, at least SwiftPM and the swift build etc. commands worked. (Which in turn blows my mind even further, because if it works without any sort of GUI on Ubuntu, why couldn't they make it work like that on macOS as well?!)


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.