Hacker News new | past | comments | ask | show | jobs | submit login
SwiftWasm: Run Swift in Browsers (swiftwasm.org)
187 points by gyre007 on May 10, 2019 | hide | past | favorite | 77 comments



I love the talk on "The Birth and Death of JavaScript" by Gary Bernhardt: https://www.destroyallsoftware.com/talks/the-birth-and-death...

Highly encourage everybody to watch it and how people may interact with JavaScript more and more through things like WASM. Very funny talk too :)


The age is nigh, its already become the easiest way to run and install Safari's JavaScriptCore on every platform:

    $ wapm install -g jsc
Can then use `jsc` to execute .js, as a REPL or inline expressions:

    $ jsc -e "console.log([1,2,3].map(x => x*2).reduce((x,acc)=>acc+x))"


You can also symlink the JavaScript core framework which contains the executable there without installing anything as an alternative


There's little relationship between wasm and js.


The talk is more about the web as an application platform, and its values, coming down to OS userland. Whether that means JS or Wasm or both doesn't really matter.


The talk predicts that Js will be dead (for user space) the moment it conquers the OS. Dead in this context means it will be invisible to the app developer just like C.


At the time, asm.js looked like it was going to possibly be the universal bytecode that runs everything. WebAssembly hadn't gone public at that time.


What would be more interesting than running Swift in the browser is running Wasm on Android and iOS. That would bring some true code sharing between the browser, mobile and backend! And also easily allow constructing apps using pieces written in any of the languages that nicely compile to Wasm.


Unfortunately WASM on iOS could only be interpreted, not JITed, due to protected memory.

Also WASM works in Mobile Safari and SFSafariViewController, but not in WKWebView - which limits its interaction with an app.


Wasm is great for sandboxing so iOS could make Wasm first-class native citizen. Then Wasm module could have access to anything and everything iOS and one could write "native" iOS applications using any language that compiles to Wasm.


Is it though (a good sandbox, I mean)? A modern OS already tries very hard to be a sandbox that can run anything. What does Wasm bring to the table for iOS?

I also feel like this is just a weird year for software, because we've got Wasm making huge strides ("let's make it easy to sandbox everything like javascript"), discovered Spectre ("oops, our assumptions about javascript being a good sandbox were maybe wrong, we apparently need to use hardware-enforced process separation"), but also many other permutations of these things in other spaces (such as the WSL2 announcement of a new integrated Windows-Linux environment, vs. containers vs. VMs vs. WSL1 vs. Wine vs. micro-services).


Why not just compile the Swift to native Android and iOS code?


Because Wasm could be used mobile as a native first class citizen, not limited to running within a browser or some browser view. And then Wasm code can be shared between multiple environments including mobile, browser, edge (CloudFlare workers), backend (multiple Wasm runtimes are emerging right now and some of then are very performant). And then one would not be limited to Swift but could use any language that compiles to Wasm. So code reuse would effectively skyrocket.

Wasm can be used in every corner of computing spectrum. It doesn't mean it's some perfect tool to solve all problems but it can lead to interesting places and those are worth exploring.


Honestly this reads like a solution in search of a problem. Native code will be faster in every way.

Wasm's strengths are in running untrusted code - its sandbox is quite strict. So the use case for wasm on mobile is downloading code dynamically. Wasm's competition in this space is JS, not native code.


> Native code will be faster in every way.

Sure, but I believe a lot of people will be willing to make a performance tradeoff for that convinience.


Not sure about the OP but personally I use WKWebView in a few places to render some HTML from a server for parts of my app that a user can then interact which needs to run some JS. For me it could mean being able to keep more of my app in a single language and port peices of it to other platforms.


There is also https://www.elementscompiler.com/elements/default.aspx which is a pretty good compiler and webassembly is one of the compile targets.


This could be really cool given that Swift is already very JavaScript-like (Edit: TypeScript, really). A JavaScript-like that you can run on the web and is just faster out of the box is appealing.

Now if only Apple would put more effort into cross-platform support for Swift...


You're getting a bit of flak for this, but I actually think it's a valid comparison.

While it's not intentional, but there's a fair level of similarity between the techniques I find myself using in Typescript and Swift – to the point where I've been able to transcribe some Swift code into Typescript when porting between platforms. Something to do with the "feel" of the language, maybe?

Swift is definitely one of my favourite languages to work with – something about the style of programming it invites just seems to click with me. I agree it would be really nice to use it more extensively, because so far it's just been a single-purpose language and that seems like a bit of a shame.


I agree. And I think Rust is like JS too. I think it's the mix between functional and imperative code.

Under the hood, JS and python are very similar, bit idiomatic JS and idiomatic Python couldn't me different. To me, idiomatic Swift/Rust feels like idiomatic JS, whereas idiomatic Go is more like idiomatic Python.


Swift is not at all Javascript-like, I think. Interesting.


Swift is like JavaScript/TypeScript only if you don't know Swift that well...

They are so different, only very superficial comparisons of syntax would lead to such a statement.


I don't know Swift that well, but this was my immediate impression when I spent a couple hours with it (and I've used C, C++, Java, C#, Python, etc.).

The array/dictionary literal syntax (especially dictionaries) was probably the main thing. Lots of languages have similar array syntax (though fewer have the auto-grow behavior), but I can't think of another C-like language with first-class, dedicated dictionary syntax.

C-likes also don't often have first-class functions/closures, or named function parameters (JS doesn't technically have the latter, but it effectively does with object destructuring; this is one of the syntax niceties Swift added).

I didn't mean to imply they had an overall similar set of features, so much that someone who's comfortable with TypeScript would have a pretty easy time warming up to Swift, which matters on the web.


Syntax is ultimately a fairly minor aspect of languages. The reference and value semantics, the memory management, the type system, the language runtime, these are what really create a development experience in a particular language. And they are on nearly opposite sides of the spectrum between Swift and JavaScript. If you are only superficially doing something in the language, a somewhat trivial project or just experimenting, then they might seem more similar than they really are.


> C-likes also don't often have first-class functions/closures

I think C is the only remaining C-like language not to have first-class functions. And there are compiler extensions for that too.


My understanding is that in cases like Java and C++, the lambdas aren't truly first-class; they come with limitations. I could be wrong.


That's true about Java but not C++. C++11 introduced true lambdas, but Java's idea of lambdas is rather laughable by comparison and nowhere near as flexible.


Right, both have sort of C-style syntax. That’s pretty much the beginning and end of their similarities.


How is Swift JavaScript-like?


Syntactically it's like someone took TypeScript and said, "what are a couple of tweaks we can perform to make it slightly more ergonomic, and also how do we get rid of the garbage collector".


No. They are both typed languages but the feature set is not even comparable. Swift is a huge language


I'm not saying they're equivalent, I'm saying if you're used to reading TypeScript then Swift will be very familiar, syntactically. That matters if you're thinking about splitting your codebase across two languages.


>Now if only Apple would put more effort into cross-platform support for Swift...

You made the mistake of thinking Swift is a programming language and not just the Apple API.


Swift currently supports Linux and has unofficial support for Windows. It's open-source and compiles via LLVM. Commercially Apple has been unenthusiastic about fleshing out its support for non-Apple platforms, but the open-source community has partly filled that gap and there's lots of enthusiasm in the community. Given the recent decline in Apple's hardware sales, they could be heading for a Microsoft-like rebirth into a company that's forced to play nicer with others.

https://forums.swift.org/t/swift-as-a-cross-platform-languag...


There is almost zero application for Swift outside of an Apple environment. I'm willing to bet there is precisely zero production code written in Swift for Windows (or Linux).

Anyhow, the Windows API (.net, C#) is better and has a brighter future and present.


Like I said, Windows support is currently middling. I would bet there's some Linux production code in Swift, though not much. But both of these are cultural problems, not technical ones. If Apple said tomorrow, "we're going to go all-in on making Swift a universal programming language", thousands of developers would cheer and jump on-board. The main thing holding it back right now is lack of confidence in its support; people don't want to invest in a new cross-platform codebase that might have its legs cut out from under it in a couple of years.

Swift is much closer to the metal than .NET, and it has very innovative syntax features. It's more analogous to Rust than to C#. .NET is a strong cross-platform ecosystem, but it's silly to say "we don't need any others because this one's good enough". It's not even the strongest one that currently exists - probably the JVM is. It honestly just sounds like you're hating on Apple for the sake of it.


[flagged]


Please don't be snarky or argue in the flamewar style.

https://news.ycombinator.com/newsguidelines.html


Superficially it has a lot in common with JavaScript (really, TypeScript), but like Rust it compiles to a native binary and doesn't need a runtime environment (C# and Java do). Also like Rust, it frees the user from manually managing memory, despite lacking a garbage collector. This combination of features makes both languages very exciting. I'm not aware of any others right now that can claim the same.

I also haven't heard of it being outperformed by Java and C#; do you have a source for that claim?


In microbenchmarks like https://benchmarksgame-team.pages.debian.net/benchmarksgame/... / https://benchmarksgame-team.pages.debian.net/benchmarksgame/... , Swift is mostly equivalent to Java with a few outliers both for/against Swift. Rust outperforms Swift fairly consistently and sometimes quite considerably. Of course, real apps may be different.

The book iOS and macOS Performance Tuning ( https://www.amazon.com/iOS-macOS-Performance-Tuning-Objectiv... ) has pretty damning benchmarks against Swift versus Objective-C even without using any tricky optimizations (not what you originally asked but something to consider). Of course the whole book (written by a former Apple engineer IIRC) is pretty much full of performance gotchas across many Apple frameworks/APIs, but the chapter on Swift was pretty harsh and basically said Swift fails to live up to its name versus Objective-C (at least at the time the book was written).

I think most people think that Swift performs like Rust/C++/C since it doesn't have a garbage collector and imagine ARC is providing relatively free memory management, but it seems Swift performs closer to languages with a garbage collector due to the various design constraints on the language (interoperability with Objective-C, ARC isn't free, and maybe without the explicit lifetime/ownership declarations in the code like Rust, ARC can't be optimized as well).


That's interesting and surprising. I definitely had the perception you described toward the bottom.


I know multiple teams who have Swift in production on Linux servers


Alright, well, don't do that.


Why not? Dive in, the water’s great.

https://vapor.codes


ballsy slogan they got there


yeah their marketing isn't great


Why not?


Seems that swift is gaining a lot of traction. It has also have drawn interest in the Machine learning community


Can someone explain to me what makes Wasm any better and/or different than Javascript bytecode.


WebAssembly has 64-bit integers and 32-bit floating points, which is difficult to do fast in JavaScript because everything is 64-bit floating points there. (32-bit integers are exact in 64-bit floating points, so that works.) This is the main advantage.

WebAssembly is also easier and faster to parse for now, but won't be for long, because JavaScript binary AST work is in progress: https://github.com/binast

JavaScript has better access to DOM and is superior otherwise.


And wasm is a compilation target for languages that aren’t JS, a pretty big advantage in my book


JS also is a compilation target for languages that aren't JS, so that is no advantage. What advantage there is boils down to 64-bit integers and 32-bit floating points.


JS is not a real compilation target for compilers like LLVM and to suggest to the contrary is silly.

JS is a transpilation target and not really for many low level languages.


> JS is not a real compilation target for compilers like LLVM [...].

> JS is a transpilation target

Transpilation is a subset of compilation, so if it is a transpilation target it is, by definition, a compilation target.


Wouldn't fixed 64-bit integers be more of a memory usage issue than performance? I'd argue that having to decide between 32 and 64 would unavoidably add some slow down.


WebAssembly 64-bit integer arithmetics compile to machine instructions on 64-bit architectures. To do that in JavaScript, you need to pattern match on long multiplication emulated with 32-bit integers.


Wasm exists, whereas there is no standard JavaScript bytecode specification.


i really really really like swift. it's by far the best language i've ever used but i wish it weren't so "monoculture" (ios dev). i guess this is good for that but i really wish the open source port of foundation were the focus of the community.


I feel like the open source port of Foundation is in pretty good shape (especially compared to a few years ago). The really important classes are mostly complete ([0]); all that's left is primarily some of the advanced networking features (but many real-world networking applications use swift-nio instead anyway). I think what's most important is 1) language refinements via swift-evolution, and 2) projects which bring Swift to more domains, such as this for the client-side and Vapor for the server-side.

[0]: https://github.com/apple/swift-corelibs-foundation/blob/mast...


The number of Linux issues on bugs.swift.org is still significant. Even when code compiles on Linux, it often doesn't work without crashing, or has different behavior. As someone who has tried to port (non-GUI) Swift code from Mac to Linux, I'd say there's still a ways to go.


It's not always perfect, but it's certainly much more stable than it was a few years ago, and it continues to improve with each release. A few years ago I had to spend weeks with each new Swift release debugging segfaults and working around Foundation bugs and missing features, but lately my Mac-tested code usually works just fine on Linux (except for the occasional problem with C library dependencies or platform-specific APIs).


Compile times and binary sizes are still issues although. There is a lot more optimization work left to do. It's a C++ v2 for a lot of the decisions they have made. And it doesn't scale that well when you have large code bases compared to other languages.

Something like a javascript / flutter style hot reload really accelerates your dev cycle and I wish Swift had it too.


I maintain a non-trivial Swift app and while compile times are indeed longer than those of Objective-C, it’s nothing insurmountable and has improved a lot on the past couple of years. To me it’s more than worth the trade with all I gain with Swift compared to Obj-C.

Hot reload is nice but to me is far from a dealbreaker, especially after your app is past the phase where you’re writing a bunch of new UI.


I completely agree. I currently use Rust for all my cross platform use-cases. I'd love to have the same kind of library ecosystem ("crates") with Swift that I get with Rust. I hope we will get there slowly, with this and now that Windows almost works.


i use rust too and some of the quality of life features from swift would make rust as good as swift, if not better. ?? rather than unwrap_or, as? and try?, if let, guard let. maybe there are reasons rust didn't incorporate this sugar having to do with the borrow checker i don't know but jeez i feel so burdened with boiler plate when i deal with optionals in rust.


Rust has if let. It can't chain them yet, but the proposal to fix it (RFC 2497) was accepted and implementation is in progress.


But Rust lacks `guard let x = a else { return }` which is one of the nicest additions of Swift. I know there were attempts to add it to Rust, but somehow the community really doesn't like it because a `let x = match a { Some(a) => a, None => return; }` is too similar. However I feel that guard also expresses the intent.


I frequently define a `guard!` macro in Rust that does exactly that. Seems clean enough to solve at the macro level -- doesn't necessarily need to be built into the language itself.


This kind of stuff should be on the stdlib if it's meant to be idiomatic.


Rust errs on the side of not putting things in the stdlib. Even things like random number generation or regexes are not in stdlib.

The excellent package manager (Cargo) makes this a non-issue.


As a contrary view, I find the boilerplate helps when I revisit a Rust project months later.


If you'd like a lower friction yet similar speed / systems language. I'd highly recommend playing around with Nim. It is exceedingly pleasant and easy to use.


sure but honestly how much traction does it have?


Certainly not as much as Swift, but enough to make joining our community[1] fun :)

1 - https://nim-lang.org/community.html


>programming language developed by Apple Inc

I would be too worried about Apple going full Apple and screwing devs to ever learn Swift.

I think this is a permanent disadvantage for anything B2B.


C#/.Net has done fine despite its birth in a company with a far worse reputation for abandonment. Same for Go.


Java ending up with Oracle was a bit of a worst case scenario as well, yet people still write Java. Exclude languages originating with a big corporate sponsor or owner, and that's half the development ecosystem gone.


Yes, I mean look what just popped up today: "Microsoft Throws in the Towel on UWP, Elevates Win32"

https://news.ycombinator.com/item?id=19883351

Before I jumped ship to the Apple ecosystem around 10 years ago, I was even then already sick of Microsoft abandoning or being indecisive about their platforms.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: