386 points · by runesoerensen · 9y ago · 140 comments
This alone is grounds for opening and drinking very expensive champagne and/or wine.
Can I finally extract a substring from the middle of a string using integer offsets, in one line? Something like string.utf8.substr(3, 5)?
Or does it still take an absolutely insane and unacceptable 4 lines of code with throwaway temp variables to track the start and end indexes? The inability to do basic string manipulations is a major turnoff, to the point it makes the entire language look like a bad joke.
The existing solution to this problem already uses integers (the offsetBy arguments)! I'm not talking about refactoring the String type, or breaking backwards compatibility. There would be no change in how the underlying String storage or access works. It's about adding a level of (zero overhead!) abstraction to simplify a common, basic operation.
Every other language I've ever touched has easy to use substrings. It makes absolutely no sense that Swift requires assigning throwaway constants to represent the start and end indexes for a simple substring extraction. There's this level of superiority regarding the purity and correctness of Swift's String type that clouds developers' ability to see that there is no limitation to doing this. It blows my mind that the most modern major language is this clunky.
String(s.dropFirst(3).prefix(5))wine.insert("Champagne")
enum Booze: String {
case wine,
case champagne,
case beer,
case whiskey
}
let wine = [Booze.champagne]
</ocd> enum Booze {
case Wine(region: String)
case Beer
case Whiskey
}
let drink = Booze.Wine(region: "Champagne")
Now.. Anyone want to demonstrate how to use enums for the wine region or, say, whiskey subtypes? Should we use classes?But yes, in Swift, arrays, dictionaries, sets and strings are all mutable. They are also value types, so mutation is a purely local effect.
var counter = 0
func foo(x: inout Int) {
x += 1
print(counter)
}
foo(x: &counter)
Note how 'counter' is read by 'foo(x:)' during an inout access of the same value. This is now prohibited by Swift 4, using a combination of static and dynamic checks.This fixes some undefined behavior and will also enable more aggressive compiler optimizations to be added in the future.
I don't know swift at all. but from their document on swapAt() it looks like they are trying to prevent two fn(&p, &p) where func fn(a: inout Type, b: inout Type)
No, see Mike's comment here.
It's not clear to me in your example why reading the value of counter after mutating it is bad; why is this now prohibited?
Of course, it would be inefficient to do this all the time, so Swift will optimize copy-then-writeback to just passing a pointer to the original storage whenever it can. But this is an optimization operating under the "as if" rule: as long as it works as if it does a copy-then-writeback, the compiler can make it actually do whatever it wants.
If the example code were legal, then it would have to print `0`, because the writeback to `counter` doesn't happen until the end of the function. That means the compiler couldn't just pass in a pointer to `counter`, but would have to actually go through the copy-then-writeback procedure it's supposed to do, so you'd lose out on optimizations.
Instead, Swift makes it illegal. You can't access a value while this call is happening. That allows the language semantics to coexist with optimizations.
"Swift has always considered read/write and write/write races on the same variable to be undefined behavior. It is the programmer's responsibility to avoid such races in their code by using appropriate thread-safe programming techniques."
"The assumptions we want to make about value types depend on having unique access to the variable holding the value; there's no way to make a similar assumption about reference types without knowing that we have a unique reference to the object, which would radically change the programming model of classes and make them unacceptable for the concurrent patterns described above."
Sounds like a system in the vein of rust but more limited, with more runtime checks and no lifetime parameters, falling back to "programmer's responsibility" when things get hard. The last paragraph makes it sound like one of the motivations is in enabling specific categories of optimizations, as opposed to eliminating races at the language level.
One of my biggest questions as a reader is how a language like C handles these cases that Swift can't handle without these guarantees. Is this a move to get faster-than-C performance? Does C do these optimizations unsafely? Is there some other characteristic of Swift that makes this harder than C? Closures get a lot of focus in the article...
> Is there some other characteristic of Swift that makes this harder than C?
Yes:
1. Swift doesn't have pointers.
Instead, you have a lot of copying of value types, and the compiler has to do its best to elide those copies where it can. For instance, at one point the document mentions:
> For example, the Array type has an optimization in its subscript operator which allows callers to directly access the storage of array elements.
In C, C++, or Rust, you can "directly access the storage" without relying on any optimizations: just write &array[i] and you get a pointer to it. The downsides are (a) more complicated semantics and (b) the problem of what happens if array is deallocated/resized while you have a pointer to it. In C and C++, this results in memory unsafety; in Rust, the borrow checker statically rules it out at the cost of somewhat cumbersome restrictions on code.
2. Swift guarantees memory safety; C and C++ don't.
This goes beyond pointers. For instance, some of the examples in the document talk about potentially unsafe behavior if a collection is mutated while it's being iterated over. In Swift, the implementation has to watch out for this case and behave correctly in spite of it. In C++, if you, say, append to a std::vector while holding an iterator to it, further use of the iterator is specified as undefined behavior; the implementation can just assume you won't do that, and woe to you if you do. (In Rust, see above about the borrow checker. Iterator invalidation is in fact one of the most common examples Rust evangelists use to demonstrate that C++ is unsafe, even when using 'modern C++' style.)
Sure it does:
func modify(_ x:UnsafeMutablePointer<Int>) {
x.pointee = 12;
}
func main()
{
var x = 23;
print("Before \(x)\n");
modify(&x);
print("After \(x)\n");
}But memory leaks are quite easy to do with reference counting which is why Swift has some more complex syntax to prevent strong references. But it can take skill to understand when to use those techniques; the compiler doesn't always find these problems, thus there really isn't the guarantee you mentioned.
Iterators could be implemented in C++ in a safer way with some performance loss, but it doesn't seem to be a priority for anyone except the safercpp guy that posts here every now and then. STLs can enable iterator validation in a special debug mode.
C compilers must also assume that any two pointers to the same type may alias (refer to the same object). The programmer can assert to the compiler that a pointer does not alias any others used in the same scope by declaring it with the `restrict` keyword.
For most functions this won't have much effect on the generated code. Writing equivalent functions to the ones in the swift-evolution doc in C, both with and without `restrict` everywhere possible, it looks like `restrict` only has an effect on the generated code for `increaseByGlobal`: https://godbolt.org/g/W8s3BA
C doesn't address these issues at all as far as I know.
Basically Swift will keep using reference counting as its GC algorithm, but for high performance situations it will be possible to have a bit more of fine grained control over ownership.
However they want to avoid any design that might result in "fighting with borrow checker" feeling.
Some info from WWDC 2017,
https://developer.apple.com/videos/play/wwdc2017/402/
There is also a transcript.
https://developer.apple.com/videos/play/wwdc2017/402/?time=2...
[1] https://github.com/apple/swift/blob/master/docs/OwnershipMan...
I was wondering why that entry had a huge spike on reads yesterday :D (1500 reads against a daily average of 200).
Objective-C does have meta-programming features [0] and that's how all the really nifty features were made possible (KVO, CoreData, etc)
What Swift is aiming for, is to be a performant, general purpose programming language. This restrains it in the amount of clever stuff you can do. That and the inter-op requirement has been an incredible hurdle when it comes to focusing on features that people actually want out of Swift.
A lot of effort has gone into being able to use Swift with existing Obj-C libraries - I sincerely hope they'll at some point say 'no more interop, only Swift, and by the way we've rewritten the UI libraries to use generics, so that you can do more than cute generic demos in your code.'
[0] https://genius.com/Soroush-khanlou-metaprogramming-isnt-a-sc...
currently has no meta-programming features, in the interest of performance
This is a false dichotomy.It seems like the language still needs some time to be completely mature, or am I wrong? I haven't used it since 1.0
I understand why they do it, but I don't like that they are getting away with it. Apple seem to be in this endless update cycle where they change stuff across hardware, operating systems and even programming languages. The customer doesn't have much choice: they either keep up or get left behind.
Try to make use of the JavaBridge, MacRuby, Quicktime, Carbon, Objective-C GC.
I can get a few more examples if you wish.
I'd much rather have breaking changes than having to constantly deal with dangling pointers and excessively verbose syntax.
So I presume you:
a. get every major design decision on a project right on the first try
OR
b. don't care and let people live with bad design for the lifetime of the product
It's already possible to do so to, by the way.
What I think go has over swift is the complete independence from platform. You can write go code on osx and compile it to a linux binary and it Just Works!
Swift on Linux is not perfect yet, though it can be made to work with some effort.
Concurrency is at the level of proposals currently, so it'll be another couple of years until they come up with something, and another couple until good server libraries/frameworks figure out how to use them properly.
It's a shame really - I imagine this could've been moving along at a faster rate had Chris Lattner stayed on with Apple and recruited some extra help.
He has written a really nice proposal for concurrency, that'll definitely influence Swift going forward. [0]
[0] https://gist.github.com/lattner/31ed37682ef1576b16bca1432ea9...
In Go, Erlang and Nodejs packages don't need to make any decisions about what kind of concurrency to use. The postgres driver in go will expose a blocking API, and the postgres driver in node will expose a continuation-passing-style API, or use promises. Everyone who uses those languages already knows how to consume those APIs. In these languages its very hard for an experienced developer to make concurrency mistakes - you can instead spend all your time thinking about the actual problem you're trying to solve.
In C, Swift and Rust this isn't true (yet). Despite all three of these languages having lots of tools for concurrency, the lack of standardisation means you can't just grab any postgres library. You also have to look at how that library does threading and figure out how to correctly integrate it with the threading model you're using in your own code. (Does it depend on tokio? Does it use posix threads? GCD? Green threads? Async?). This turns the 3rd party package ecosystem in these languages into a fragmented minefield.
As far as I know there are 4 main swift-based http server libraries[1] at the moment. Each one works slightly differently. Because they all roll their own concurrency tools, they're all mutually incompatible. Each one has implemented its own static file server, its own hsts header middleware, its own json parser, etc. I'm not sure about erlang but in node and go because the concurrency primitives are standard, they're all similar enough that you can migrate code between them or wrap a tool thats designed for one to work for another.
(Of course rust has tokio, but tokio is being rewritten[2]. Rust also has mio and raw threads. In a few years we'll probably have strong standards for both swift and rust, but until then the ecosystems will be a mess compared to the bliss of node and go.)
[1] https://medium.com/@rymcol/current-features-benefits-of-the-... [2] https://tokio.rs/blog/tokio-reform/
You can use Grand Central Dispatch, and it works. It's not as wonderful as go routines and channels, but hey, it works.
That's just false. Server-side projects that require concurrency are a tiny minority.
1. Lattner's ability to present complex topics in an approachable way is very impressive. 2. I'm really excited for Swift 8.0 (my best guess at the first version that will include all this).
According to the documentation at perfect.org, it supports asynchronous request handling.
I've tested it locally a while ago and IIRC it could utilize multi-cores just fine.
Edit: REPL stil doesn't allow importing Glibc by default, you need to specify the include path manually (e.g. swift -I /opt/swift-4.0-RELEASE-ubuntu16.10/usr/lib/swift/clang/include/).
Compared to Rust it is considerably easier to learn.
Go is probably easier to learn than Swift but Swift is a lot more expressive. You could do scientific computations in Swift but that would be cumbersome in Go since you can't easily define matrix, vector and point types yourself.
---
Swift and Kotlin evolved at about the same point in time with the same contemporary languages around them. And so the surface-level syntax does look very similar. … But if you go one level down below the syntax, the semantics are quite different. Kotlin is very reference semantics, it’s a thin layer on top of Java, and so it perpetuates through a lot of the Javaisms in its model.
If we had done an analog to that for Objective-C it would be like, everything is an NSObject and it’s objc_msgSend everywhere, just with parentheses instead of square brackets. And a lot of people would have been happy with that for sure, but that wouldn’t have gotten us the functional features, that wouldn’t have gotten us value semantics, that wouldn’t have gotten us a lot of the safety things that are happening [in Swift].
I think that Kotlin is a great language. I really mean that. Kotlin is a great language, and they’re doing great things. They’re just under a different set of constraints.
---
However, I wish the mac release was available as independent binaries without having to come along with Xcode.
If they’re not already installed, running one of those commands will prompt you to install them.
brew install swiftenvYour second comment is being voted down because ePub works just fine in iBooks and on iPads for many of us, again, you need to provide details.