Swift 4.0 Released
swift.org
swift.org
This alone is grounds for opening and drinking very expensive champagne and/or wine.
wine.insert("Champagne")
But yes, in Swift, arrays, dictionaries, sets and strings are all mutable. They are also value types, so mutation is a purely local effect.
let array = [1, 2, 3] var mutableArray = [4, 5, 6] var anotherMutable = array
Not sure how much optimisation is done under the hood, but Swift compiler loves to complain about mutable structures that are not ever edited.
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?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.
String(s.dropFirst(3).prefix(5))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.
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.
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.
It's good for code readability but also prevents accidentally passing a variable to a function that could mutate it when you weren't expecting that, and vice-versa.
The purpose is to allow for out-parameters. A classic example would be the `+=` operator. (Swift operators are just normal functions with special call syntax.) It takes its first parameter as `inout` so that it can mutate the value.
Note that inout parameters work with expressions where it would be impossible to take the address. For example, you can use & on a computed property that has a setter. In that case it has to read the initial value, pass that to the function, then write back the new value, because it has no idea where the computed property actually stores the value, if anywhere.
Edit: because I'm obsessive and weird, I made a quick example of this computed property stuff:
http://swift.sandbox.bluemix.net/#/repl/59c284376cbea87f72c4...
Click the play triangle at the bottom to see the output.
Coming from Haskell and Rust it's nice to see this trend catching on.
Is Swift planning to introduce a distinction between borrows and mutable borrows to the user? From what you describe it seems like right now syntax-wise a borrow and a mutable borrow look the same, and the runtime makes some decision about it.
edit: Or I guess it could be the opposite. Since Swift passes by value always unless the runtime can optimize (right?), you could just not write & and inout and cross your fingers it gets optimized to a borrow rather than a copy?
Stuff like this makes me prefer the explicitness of Rust. It seems like here on the surface it's abstracted from you, but really you need to know the rules anyway or you could get into trouble.
[1]: https://github.com/apple/swift/blob/master/docs/OwnershipMan...
I find it hard to believe that 'large structures are rare in Swift'. People don't make structs with multiple fields? You never want other structs to hold one or many of those? These are cases where non mutable borrows are useful. I understand that in Swift this is probably abstracted away from you and done by the runtime (or compiler) if it can, but that doesn't mean non-mutable borrows aren't useful; you just probably don't see them.
Of course, that's just a guess, I don't know Swift.
As far as large structures go, I'm thinking "large" like hundreds of fields. Any time I've seen people concerned about large structures, they misunderstand the value-typedness of things like String and Array and are worried about the contents of those things, which isn't really part of the size of the struct itself. But that's just what I've seen.
I'd guess that Swift also has something analogous to an array slice, which would be a (possibly) immutable borrow to a chunk of array data on the heap. This also happens to be a good use case for borrows.
From the other comment here it seems like Swift is pursuing an ownership model similar to Rusts, in which case, immutable borrows will become more important when you think about struct contents. You can only have a single owner, but you can specify many borrowers. This kind of thing is important when you have an array or vector of types, often you don't want those types to have a single owner but you want them to be populated or store a reference from somewhere else.
Anyway, don't dismiss the concept out of hand. Immutable borrows definitely have their uses, whether it's made explicit to you or not in Swift is another thing entirely.
Swift does have ArraySlice, but I don't get how borrows factor into that. Seems vaguely similar in concept, except ArraySlice exists to represent a subset of the original array, not just so you can pass arrays by reference. Since arrays are already passed by reference under the hood, that wouldn't really be useful.
I'm not dismissing the concept out of hand, so I'm not sure why you're warning me about that....
It was already like that in older languages like Lisp, Smalltalk and CLU, just C++ made them in a different way.
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.
"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...
C doesn't address these issues at all as far as I know.
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
> 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");
}https://www.cheerupemokid.com/wp-content/uploads/2015/05/201...
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.
The language includes memory unsafe constructs without marking them in any way, since it must be compatible with C.
To clarify: safe containers, iterators and algorithms can be designed, but they don't seem to be a priority of the C++ community. Personally I'm quite scared of accidentally passing the wrong iterator to some function, but OTOH I can't recall it ever happening. I don't use the debug STL either, haven't needed it.
The examples that pcwalton keeps bringing up seem artificial to me. It's true that you can't have perfect safety in C++, but with some effort and custom libraries, many errors can be caught at compile or run-time. The advantage of Rust is that it's safe by default, not necessarily that there's a major safety difference between quality C++ and quality Rust.
I’m not actually sure how frequent iterator invalidation is as a source of vulnerabilities; I don’t think I’ve ever found one of that type myself. However, use-after-frees in general (of which iterator invalidation is a special case) are very common, usually with raw pointers. In theory you can prevent many use-after-frees by eschewing raw pointers altogether in favor of shared_ptr, but nobody actually does that – that’s important, because there’s a big difference between something being theoretically possible in a language and it being done in practice. (After all, modern C++ recommendations generally prefer unique_ptr or nothing, not shared_ptr!). And even if you do that, you can’t make the `this` pointer anything but raw, and same for the implicit raw pointer behind accesses to captured-by-reference variables in lambdas.
You can definitely greatly reduce the prevalence of vulnerabilities with both best practices for memory handling and just general code quality (that helps a lot). But if you can actually do that well enough - at scale - to get to no “major safety difference”, well, I haven’t seen the evidence for it, in the form of large frequently-targeted codebases with ‘zero memory safety bugs’ records. Maybe it’s just that C++’s backwards compatibility encourages people to build on old codebases rather than start new ones. Maybe. It’s certainly part of the story. But for now, I’m pretty sure it’s not the whole story.
C++ code could be written significantly safer with a performance loss, e.g: index checking at run-time, iterator validity checking, exclusive smart ptr usage with null checking, etc. That, together with code reviews, static & dynamic analysis should IMO lead to comparable safety. That's what I'd do.
However, there doesn't seem to be a rush in that direction. My guess is that there won't be a rush to switch to Rust either.
Is the security angle that important that it's handled through education and better tooling? Or only important enough to do some code audits and pen testing?
And they do actually, in the MSVC debug mode and with libstdc++'s -D_GLIBCXX_DEBUG. But nobody ever wants to use them.
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...
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.My personal desire is to see a backwards incompatible UI layer, that makes generics usable.
As a simple example - you currently can't have a UITableViewCell<YourModel>, which's the most obvious and proper use of generics for UI logic.
So as it stands, all this work has gone into mixing polymorphism and subclassing, and yet it doesn't actually get used a whole lot, because of the existing libraries having been written when generics were not around.
I was wondering why that entry had a huge spike on reads yesterday :D (1500 reads against a daily average of 200).
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
My experience with some medium projects is that it costs me a morning every update. I'm okay with that because Swift is such a more productive and higher quality language than Objective C.
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...
You can use Grand Central Dispatch, and it works. It's not as wonderful as go routines and channels, but hey, it works.
The very motivation behind creating Swift, has been to have performance, and none of the undefined behaviour (cause of innumerable security breaches and unintentional complexity in compiler design and everyday programming) [0]
To me, grand-central-dispatch feels one small step above semaphores/locks/monitors.
There has been a lot of research in distributed computing and concurrency - I'd like to see libraries, language constructs and runtimes based on research fresher than before I was born :)
[0] http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
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.
Node became popular because now front-end devs could write their own backends.
Go became popular because of Google and it's concurrency primitives (as far as I know)
Swift is going to become popular because of Apple and... fill in the blank.
My take is that it'll take good performance, and easy to understand concurrency primitives that make writing libraries and using them a joy - that's the only way.
That'll be the differentiating factor that'll entice people to pay attention - otherwise as you have pointed out, there are plenty of alternatives.
So you are saying concurrency primitives aren't required for a successful server language?
It's a matter of time for it to get traction.
The only thing python/ruby have going for them at the moment is momentum.
Remember in 2005, Python was a fringe language on the web. Most web programming was done in php.
That's just false. Server-side projects that require concurrency are a tiny minority.
Also with the parent, why do you think "swift has no quality high-level concurrency primitives"? GCD and blocks along with some promise library should make it easier then goroutines and channels no?
Things like the core request loop and the DB connection pool will need to handle concurrency, but a few people will have figured out how to get that stuff working and you can just use their libraries.
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/
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).
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.