
The Decade of Swift - ingve
https://www.swiftbysundell.com/articles/the-decade-of-swift/
======
ardit33
I hate to say this, but Swift is to Objective-c, what Scala is to Java....

It was very exiting and promising at first, but it became bogged down due to
its sheer run-away complexity and over-academic approach to programming....

To an outsider, or iOS new comer, Swift looks much better than Objective-c,
(due to Objective-c weird syntax), but to many insiders, Swift seems like a
huge missed opportunity...

The use of Swift, outside Apple's ecosystem is going to be limited.

~~~
pavlov
For a language whose nearly exclusive use case is writing Cocoa applications,
it’s odd how Swift ignored most of what had made Obj-C so good for GUI apps.
Instead they just doubled down on everything that C++ was and Obj-C actively
had tried to avoid.

~~~
jzelinskie
Would you mind expanding on these feature sets a bit more?

Because I just started playing with SwiftUI/Combine without ever using
ObjC/UIKit, I don't know what parts of ObjC shined.

~~~
saagarjha
Objective-C was a good fit for dynamic, object-oriented GUI frameworks like
Cocoa because that’s how it itself was structured. SwiftUI and Combine are
simply a different way of structuring UI code that fits a lot better with
Swift’s strengths.

~~~
solarkraft
Could you expand on that? How do the structures differ?

------
dmitriid
> That’s why Swift’s expressive and very lightweight syntax

And a few paragraphs later:

    
    
      extension Array {
        func sorted<T: Comparable>(
            by keyPath: KeyPath<Element, T>
        ) -> Self {
            sorted { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
        }
      }
    

I can't say this is lightweight any longer.

My greatest gripe with Swift comes not from Swift itself but from its standard
library. When most new languages start with their own standard libraries that
are usually interfaces towards C APIs or POSIX, Swift's Foundation is half of
MacOS and then some.

I recently needed to read some data from a file in Swift, and it took me quite
some time to realise there was no fopen equivalent. Read/write files is a
function on String? And getting a file handle is an excercise in figuring out
proper dir names and user enums? [1]

There are a few other weird things in the language itself like guards which
IMO are an entirely unnecessary construct that can be as easily solved with
regular ifs. Or Optionals that have no way of working with them except
unwrapping them (either with ! or via guards).

SwiftUI, however, is a very interesting approach, and I hope there are more
frameworks (especially UI frameworks) like this.

[1]
[https://twitter.com/dmitriid/status/1201441652507844608](https://twitter.com/dmitriid/status/1201441652507844608)

~~~
cableshaft
The directory thing is more due to sandboxing than anything else. They don't
want someone to be able to write an app that can read anything anywhere on
your phone, so it has specific directories that have different levels of
access and temporality (i.e. one is a temp folder that gets flushed each time
you quit the app, if I remember correctly).

It's not that complicated once you look it up, and like most of this stuff,
you can mostly write wrapper classes one time to hide the gnarly bits and call
your wrapper class to do what you need to do the way you like to do it.

It's been several years since I've had it read from a file, and I actually
thought I would click that twitter link and see something super complicated,
but it's actually pretty straight-forward. Not a one-liner like some
languages, no, but as soon as you want to open something with options (like
the encoding in this one), most other languages start looking more complicated
like this as well.

Like python's open looks more like this with options: "open(filename,
mode='r', buffering=-1, encoding=None, errors=None, newline=None,
closefd=True, opener=None)". I've opened many a file in Python scripts, but
I'd have to look up buffering, encoding, errors, closefd, and opener right now
if I wanted to use them (I haven't really in the past)

And Python has 11 different access modes that I often have to look up to
remember what all my options are again: r+,w,wb,w+,wb+,a,ab,a+, and ab+

~~~
dmitriid
> They don't want someone to be able to write an app that can read anything
> anywhere on your phone,

And that's the main problem with Foundation which hurts Swift as a language:
it was made for iPhone apps, and hardly anything else. I was trying to make a
CLI app on the desktop. I gave up and used something else.

> It's not that complicated once you look it up, and like most of this stuff

Yeah, I tried to look it up. It's extremely complicated, and it doesn't help
that the documentation tends to spread all the knowledge across dozens of
pages with very terse documentation and next to zero examples.

> I've opened many a file in Python scripts, but I'd have to look up
> buffering, encoding, errors, closefd, and opener right now if I wanted to
> use them

My example doesn't have any buffering, or encoding, or anything. It's just
reading a file. There's no chance in hell you can deduce those lines from the
documnentation, or find out where to put the files to read from, or find out
that it's not the file's job to read/write data, but String type's (wat?) etc.

It doesn't help that the only real example of reading and writing files isn't
in the docs, but in a StackOverflow answer (most other examples are either
outdated, or use calls to Obj-C libs etc.)

~~~
cableshaft
It sounds to me like you're just asking for a quick and dirty default that's
nice and pithy and short. That's fine, but file i/o tends to get messy and
easy to exploit without some safeguards, and doing it "right" tends to be a
bit more complicated.

Like part of your complaint above is pathing, and even something as short and
pithy as Python (at least in my opinion, that's why I keep going to it to
write proof of concepts), in order to do file i/o "right", requires knowing
about all sorts of other things.

One thing I forgot to mention in my previous post is paths in Python, which
has this whole fun page on it in the Python documentation:
[https://docs.python.org/3/library/os.path.html](https://docs.python.org/3/library/os.path.html).
Part of the reason for this in the first place is because pathing is handled
differently between Unix and Windows systems, so you're supposed to use this
library to navigate (or something completely different, glob, which is another
thing to look up and understand) instead of just using a
open("c:/blah/blah.txt") so that it can be compatible for either OS.

That's not too much different than having to specify a type of directory for
Swift, and has the same types of reasons for why it exists, for safety, but it
just doesn't let you do something potentially dumb like open('blah.txt') for
something quick and dirty, like Python does, which I admit I do abuse if I'm
trying to write something quick and dirty myself.

EDIT: This link here shows how you can write a helper function to basically
turn the file i/o into a 2-liner, and I'm sure there's ways to make this even
simpler: [https://www.hackingwithswift.com/example-code/strings/how-
to...](https://www.hackingwithswift.com/example-code/strings/how-to-save-a-
string-to-a-file-on-disk-with-writeto)

~~~
m45t3r
> One thing I forgot to mention in my previous post is paths in Python, which
> has this whole fun page on it in the Python documentation:
> [https://docs.python.org/3/library/os.path.html](https://docs.python.org/3/library/os.path.html).
> Part of the reason for this in the first place is because pathing is handled
> differently between Unix and Windows systems, so you're supposed to use this
> library to navigate (or something completely different, glob, which is
> another thing to look up and understand) instead of just using a
> open("c:/blah/blah.txt") so that it can be compatible for either OS.

There is pathlib nowadays that allows you to navigate in very complex
situations using a quite nice OOP API.

~~~
cableshaft
Good to know, thanks :) I've only ever used Python for my own tinkering
purposes so I haven't been too aware of any new developments.

But I assume the old ways are still valid code, so if you're working with
Python code you may encounter any of now 3 different systems of just
navigating paths for file i/o, what the parent claims should be dirt simple.

~~~
dmitriid
Yes. It is dirt simple, for dirt simple things. It's quite easy _and_
discoverable from documentation for more complex things.

The method in my link (which changed rather drastically between versions):

\- is very much iOS and MacOS specific

\- requires knowledge of quite a few iOS/MacOS-related things
(FileManager.SearchPathDirectory is probably 80% Apple-specific)

\- even though it's a "FileManager", it doesn't even let you access/open a
file. You have to perform additional operations on the resulting Directory
type (.appendingPathComponent)

\- even that doesn't give you a means of opening a file, because in order to
read a file, you have to invoke a String constructor. In order to write to a
file, you need to invoke a method on a String type. Talk about coupling
entirely unrelated things

That is an example of objectively bad API design.

And it's clear from API evolution that it's not even Swift APIs. These are
very thin wrappers for _OS 's_ existing Obj-C APIs. I think it's the first
among languages: to provide OS APIs and call them a standard library for a
language. I don't think even MS did that when they were creating .NET.

~~~
pjmlp
Microsoft does it all the time with .NET, after all the future of Windows was
going to be all .NET.

It just did not worked out that way, as WinDev tanked Longhorn efforts and now
we have UWP (aka COM) instead of .NET for OS APIs.

Which are anyway easily accessible from .NET given its COM support.

------
lazyjones
Swift doesn't seem to be a bad language, but during my brief adventures with
it I encountered a major drawback: differences between versions are so great,
that searching the web for examples is problematic and you end up with many
fruitless attempts and compiler errors. Apple's documentation isn't nearly as
useful and readable as that of the Go team.

~~~
cableshaft
This was definitely true in the past, and might still be true now, I'm not
sure, but XCode does a good job of catching Swift errors now and can fix
several of them for you, and for those that don't, there mostly seems to be
useful StackOverflow answers for the error messages online now.

I took a long break from working with Swift and just started diving into it
again, and even though there was two major versions since I last messed with
it, it was pretty easy to settle into it, and I've only had to look up how to
do things on a case by case basis periodically. Maybe that's just my
experience, though, and others have a harder time with it.

------
ncmncm
I can't really imagine Swift ever breaking out of Apple's walled garden. It's
a pretty big garden, but the language concedes so much to Objective-C
compatibility, it is hard to see any role for it where Objective-C never got a
foothold.

Where am I wrong?

~~~
willyt
To install swift on a raspberry pi:

curl -s <[https://packagecloud.io/install/repositories/swift-
arm/relea...](https://packagecloud.io/install/repositories/swift-
arm/release/script.deb.sh>) | sudo bash

sudo apt-get install swift5=5.0.2-v0.4

[0] [https://lickability.com/blog/swift-on-raspberry-
pi/](https://lickability.com/blog/swift-on-raspberry-pi/)

~~~
wlesieutre
HN truncates long URLs, you’ll need to indent with spaces for a code block to
show the whole thing

~~~
willyt
Probably best just to follow the cite link and learn more about what you might
be installing. Its a random blog post I found on the internet.

------
hajile
Can someone sell me on Swift over dart or kotlin? They seem to be direct
competitors.

Since we're talking about the future of programming, can someone sell me on
Swift instead of ocaml, SML, or F#?

I don't see a good reason to pick it outside of targeting Apple devices.

~~~
rb808
> dart or kotlin? ... ocaml, SML, or F#

\+ scala, go, rust, elixir/erlang

Yeah its so much time to learn all this stuff. Its a good reason they probably
will all fade, better stick to js/python/java/C#/C++ like everyone else and
wait.

~~~
leonidasv
> better stick to js/python/java/C#/C++ like everyone else

I would change Java to Kotlin here, since Kotlin has a 1:1 interop with Java
while having goodies like null safety, type inference and functional
programming without the academicism of Scala (and its slow compilation time).

If you also account for the smooth learning, Kotlin is probably the safest bet
from these 9 mentioned.

A lot of businesses with Java codebases are already messing with it (and not
only for Android).

~~~
pjmlp
How does that 1:1 interop work for calling Kotlin co-routines from Java, or
stuff without @JVM... annotations for that matter?

------
cableshaft
Swift has come a long way. I remember first trying it and XCode acting like it
couldn't figure anything out in Swift, and you could almost never bring up an
autocomplete or search for references or jump to definitions or any nice
feature in an IDE that worked just fine with Objective-C. I decided to give it
another shot years later, and I'm working on a simple game in Swift right now,
and it's been a much, much smoother experience.

Although admittedly there's still some bizarre behavior. Like this morning
while iterating over a simple for loop, XCode decided it was just going to
stay on the final item in the collection and keep looping until my memory ran
out, over and over again, and I couldn't find anyone talking about this
online, but eventually decided to do a "Clean Build Folder" and then Build,
and that fixed it (but why did it happen in the first place? So odd!).

And it still doesn't always think a class I wrote or renamed is valid when
referencing it in another class, but a rebuild or quitting and restarting
tends to fix that.

Still, I'm liking it a lot, and having a lot of fun with Swift now. SpriteKit
is great for making games, except for the lack of cross-platform capability,
but if the game somehow manages to take off, I can write some wrapper classes
to have the same behavior as most of the SpriteKit classes I use and port it
easily enough.

~~~
Andrex
Most of these all sound like improvements to XCode, not Swift?

~~~
cableshaft
I guess I should say "My experience in working with Swift has come a long
way", because XCode being so crap with it made it a pain in the ass to code in
Swift back then, for me, especially considering how rock solid Visual Studio
is in comparison.

To be more specific about Swift, though, there used to be a ton of things you
had to bridge to Objective-C in order to do back then, and now it seems like
there's almost nothing you have to bridge to Objective-C to do unless you want
to work with your legacy code (all of their libraries now have Swift support,
at least those that I use), and there's now a cool new SwiftUI framework that
is very easy to use and very powerful.

------
geophile
I like a lot about Swift: strong typing, good support for closures, reasonable
abstractions. But there's a lot that I dislike too. A lot. In general, I find
the language to be far too trendy and fussy. I get the impression the design
was guided by the goal of streamlining snippets of code meant to highlight
cool features, gaining undesirable complexity as a result. One example: Do we
really need $n function parameters? In just about every other language, a
function has parameters, period. Those names are used inside the function.
Depending on the language they may be used outside the function too. Swift
separates those inside and outside views, permitting different names for both.
And then allows for no names at all! I don't care. $n parameters seem to come
from primitive languages like sh, and should have stayed there.

get/set/didSet introduces ridiculous complications just so we can pretend that
a large number of function invocations look like assignment statements. This
was a cool idea in C++, briefly, and then we discovered that having arbitrary
code hide behind what looks like an ordinary assignment statement was a bad
idea.

Extensions also remind me of C++ excesses. It is difficult to look at a piece
of code involving a variable some type and be sure that I understand how that
type works. The problem is that the code implementing the type is not in one
place. There is the type definition, but then there are extensions. Possibly
many of them. Defined all over the place.

I really dislike the irregularity surrounding let. In one context in unwraps
an Optional. In another context it does not. Why?

I got off the Swift train at the release in which associated types were
introduced. I'm sure it solves some actual problem, but it sure wasn't clear
at the time. (The project ended -- it's not that I decided to go back to
Objective C.)

Reference counting is far too intrusive, and it is easy to get it wrong in
subtle ways. I find Java's (!) memory model relatively simple, and that's
saying something. I understand why reference counting was chosen over GC. I
don't have a good answer, but reference counting is just ugly. I actually
think I prefer the C/C++ model of explicitly freeing memory.

~~~
setpatchaddress
I certainly don't disagree that there's too much C++ in Swift (the Swift
architects write C++ for a living, not ObjC, so it's hardly surprising) but
it's not due to trendiness. Most of the features you mention derive from
direct experience with Objective-C. Function arguments, property accessors
(get/set/didSet), extensions (categories), etc. Every one of these things
solves a real problem in the field.

I don't understand your comment about reference counting being intrusive.
Apple's implementation, ARC, used in Swift and modern ObjC, is essentially
invisible to you if you're using native objects.

~~~
fauigerzigerk
_> I don't understand your comment about reference counting being intrusive._

It's intrusive because you can never really stop thinking about it if you want
to write correct code. Here's an example from a very interesting article by
Mark Sands [1]:

How quickly can you tell whether or not this piece of code has a reference
cycle?

    
    
        class ServiceLayer {
            // ...
            private var task: URLSessionDataTask?
    
            func foo(url: URL) {
                task = URLSession.shared.dataTask(with: url) { data, response, error in
                    let result = // process data
                    DispatchQueue.main.async { [weak self] in
                        self?.handleResult(result)
                    }
                }
                task?.resume()
            }
    
            deinit {
                task?.cancel()
            }
        }
    

In my view, reference counting does not combine very well with heavy use of
closures.

[1] This is an interesting read: [http://marksands.github.io/2018/05/15/an-
exhaustive-look-at-...](http://marksands.github.io/2018/05/15/an-exhaustive-
look-at-memory-management-in-swift.html)

~~~
Matthias247
> How quickly can you tell whether or not this piece of code has a reference
> cycle?

I'm curious. Does it? I would have guessed the "weak self" would have
prevented it.

> In my view, reference counting does not combine very well with heavy use of
> closures.

It's one of the area where one has to be careful for sure! C++ with smart
pointers and callbacks exhibits the same problem. And GC based languages make
the pattern easier for sure. However I think this is not even the most
critical error source in callback based designs. I think threading issues due
to callbacks being executed on different threads cause the most trouble.

Therefore I think languages like Javascript and Dart - which only offer a
single thread AND GC - are the the easiest to use for callback based designs.

~~~
fauigerzigerk
Yes, there's still a reference cycle because the outer closure implicitly
captures self as well. The article explains it in greater detail.

I agree that threading is another big gotcha, arguably a bigger one. Rust has
some mitigations against that sort of thing.

------
bsaul
I’ve recentried tried google trends to see if swift was gaining popularity
overall :

[https://trends.google.com/trends/explore?date=all&q=%2Fm%2F0...](https://trends.google.com/trends/explore?date=all&q=%2Fm%2F010sd4y3,%2Fm%2F0_lcrx4,%2Fm%2F09gbxjr,%2Fm%2F0h52xr1,%2Fm%2F0n50hxv)

Imho There’s definitely an issue in the strategy for this language ( or for
ios native development since the two are tied).

My guess is cross platform development is eating mobile, and swift has nothing
in that area.

------
m_ke
With Chris Lattner's move to Google and the state of Java it would interesting
to see Google embrace Swift and add official support for it to Android.

~~~
6700417
This seems very unlikely to me.

They would need it to interoperate with their existing stack. They chose
Kotlin where they reasonably could have chosen Swift and then worked to extend
it to work with their existing stack.

Judging by what I would argue has been a lukewarm reception to Swift for
Tensorflow, I think it would a very hard sell to convince people within Google
to support Swift as a first-class language in the rest of their ecosystem.

They could for example start by adopting Swift for server-side programming for
Google cloud and they seem to be putting no effort into that, at least public-
facing effort.

~~~
m_ke
I'm pretty sure they went with Kotlin before Swift was open sourced, but I
agree with you that the likelihood of them doing it is very low.

Swift for Tensorflow hasn't gotten much traction because the overlap between
programmers who know swift and machine learning engineers is super tiny.
Making the core language differentiable sounds very promising though .

~~~
6700417
Swift was open-sourced 18 months before Google announced support for Kotlin.

There was probably several months or more of debate and work within Google by
the time of the announcement, but it seems reasonable that during those 18
months they would have also considered and rejected Swift.

~~~
skohan
It's an interesting value proposition to consider. From one side, Google could
have stood to gain by potentially luring the legion of iOS devs onto their
platform. At the same time, it's hard to imagine them surrendering any part of
their product to a language which is ultimately controlled by Apple at the end
of the day (although I suppose they could fork it).

In any case, open source Swift was not ready for prime time at time of
release.

------
sys_64738
> due to Objective-c weird syntax

Objective-C is simply regular C with Smalltalk objects added. If you know
Smalltalk and you know C then you're golden.

------
carlhung
I love swift. but i think it is getting lack of traction.

