What language is more memory safe, Swift or Rust?

I know Swift is a memory safe language and I also know that Rust is a memory safe language so my question is what language in general is safer? Are they on par or is one better than another? I'm a Swift and Rust developer and by the complexity of Rust I've just assumed Rust is safer but I never really knew for sure.

Swift is only memory-safe in single-threaded environment, unlike Rust, which can prevent data races at compile time.

3 Likes

@broadway_lamb Oh alright, I appreciate the response thanks!

Some of the complexity of Rust makes it possible to prove the absence of data races (under certain global assumptions). For example, Rust's type system can prevent you from sharing an unprotected reference to mutable memory across threads. This complexity does make Rust safer than Swift in the presence of concurrency; Swift has to rely on the programmer to avoid data races, at least for now.

Some of the other complexity of Rust makes it possible to safely express certain interesting things in local scopes. For example, in Rust you can build an array of references to the elements of another array, and you can then pass that around freely as long as it doesn't escape the lifetime of the original array. You can see this as adding safety, since if you wanted to express exactly that in Swift you would need to use unsafe abstractions and thus lose some memory-safety. Alternatively, you can see it as a complexity/performance trade-off, since there are probably ways to achieve the programmer's original high-level goal that don't require an array of references into another array (perhaps less efficient ways), and the ability to express this undoubtedly adds complexity to the language.

I tend to think that most of the user-facing complexity of Rust is in the second category. That said, the first category is very important, and it's unfortunate that Swift still doesn't have a great answer for it.

23 Likes

Neither of them have traditional garbage collection. Rust has compile-time garbage collection, and Swift has ARC, and Rust's garbage collection does a much better job than ARC, so I would go with Rust, just avoid using unsafe blocks.

Terms of Service

Privacy Policy

Cookie Policy