The Swift Programming Language
developer.apple.com
developer.apple.com
Software-wise, I feel these current WWDC announcements are the most exciting in years.
Looking at the Swift docs right now, I can see many interesting inspirations at work: there's some Lua/Go in there (multiple return values), some Ruby (closure passed as the last argument to a function can appear immediately after the parentheses), closure expressions, strong Unicode character support, a very very neat alternative to nullable types with "Optionals". Operators are functions, too.
It has the concept of explicitly capturing variables from the surrounding context inside closures, like PHP does, instead of keeping the entire context alive forever like Ruby or JS.
Hell there is even some shell scripting thinking in there with shorthand arguments that can be used as anonymous parameters in closures, like "sort(names, { $0 > $1 } )".
Inside objects, properties can be initialized lazily the first time they're accessed, or even updated entirely dynamically. Objects can swap themselves out for new versions of themselves under the caller's nose by using the mutating keyword.
There is the expected heavy-weight class/inheritance scheme which accommodates a lot of delegation, init options, bindings, and indirection (as is expected for a language that must among other things support Apple's convoluted UI API). But at least it's syntactically easier on the eyes now.
Automated Reference Counting is still alive, too - however, it's mostly under the hood now. Accordingly, there is a lot of stuff that deals with the finer points of weak and strong binding/counting.
Swift has a notion of protocols which as far as I can tell are interfaces or contracts that classes can promise to implement.
I think generally there are a few great patterns for method and object chaining, function and object composition in here.
The language has C#-style generics, and supports interesting type constraint expressions.
In the other direction, XCode will automatically generate an Objective-C header to expose your Swift code to Objective-C.
Direct link to Elm's demo similar to Bret Victor's: http://debug.elm-lang.org/edit/Mario.elm (video: https://www.youtube.com/watch?v=RUeLd7T7Xi4)
Defining Golang features that don't exist in Swift:
- Interface types with implicit adoption (Swift takes explicit protocols from ObjC)
- Error types
- Relatedly, the "damnable use requirement" and its interaction with error types and multiple value returns (ie, the reason Golang programs in practice check errors more carefully than C programs).
- Slice types
- Type switching (though, like Golang, it does have type assertions)
- "defer"
- Of course, CSP and the "select" statement.
Swift features that don't exist in Golang:
- Generics
- Optionals
- A conventional, full-featured class-model
Of the languages you could compare Swift to, Golang seems like one of the biggest reaches. Even the syntax is different.
(I like what I've read about Swift and expect to be building things in both Golang and Swift, and often at the same time).
How about a blog series where a developer implements something in Golang and/or Swift, then you explain how it's insecure? Then the developer tries to fix it and you explain something else that's insecure. Rinse, repeat.
Objective-C has informal protocols, and so does Swift.
But for others aspects that are not related these two(class system, concurrency), I would say they look quite similar.
Someone is always going to be out there saying that any language isn't ready for prime time because it lacks feature-X.
There are some things that did strike me as similar. The approach Go takes is to bring C language to a more modern world (i.e. C without some of the language burdens that we know so well). Swift is attempting to do the same. The way it does type inference is nice.
var x = "Hi" reminds me of Go's const types. The ARC usage reminds me of Go's garbage collection (even though it's not the same thing). Basically, the parts that it omits from C are similar to the parts that Go takes out of C even though the language itself is different... thankfully.
Like all the other thousands of languages with C based syntax.
> var x = "Hi" reminds me of Go's const types
Why does it remind you of Go and not of all the other languages that use 'var x = "Hi"' like JavaScript, ActionScript, C#, Scala, Kotlin?
> The ARC usage reminds me of Go's garbage collection
Why does it remind you of Go and not of all the other languages with garbage collection?
You sound old. ;)
I haven't gotten to Swift in a deep enough way, but it looks like it tried to tackle the same problems with the exception of concurrency. There are differences such as classes and generics in Swift. There are also similarities such as functions as first class citizens (or so it appears so from the closures section of the free book).
All in all, it reminds me of Go just a bit. It doesn't remind me of all of those other languages that I do not know.
Yes, Swift's semantics are different (since it's essentially a domain-specific language designed to make writing Cocoa apps faster), but syntax-wise a Go programmer feels right at home reading Swift.
Because, the keyword for function, keyword, parens-free conditionals and optional semi-colons are "the entire basic syntax" of Go, right?
Those are some of the most inconsequential details of Go syntax (all three of them), and of course all existed ages before Go.
Python has no semicolons and parens-free conditionals for one.
I'm surprised not to hear Python mentioned, as it also has a tuple syntax.
It has it all [1]: static typing, type inference, explicit mutability, closures, pattern matching, optionals (with own syntax! also "any"), generics, interfaces, weak ownership, tuples, plus other nifty things like shorthand syntax, final and explicit override...
It screams "modern!", has all the latest circlejerk features. It even comes with a light-table/bret-victor style playground. But is still a practical language which looks approachable and straightforward.
Edit: [1]: well, almost. I don't think I've caught anything about generators, first-class concurrency and parallelism, or tail-call optimization, among others.
Swift could very well render Rust almost totally irrelevant within the OS X and iOS sphere of software development. If we end up eventually seeing Swift implemented for other platforms, then the chances of Rust's long-term success diminish even more.
Things might have been different had a stable, even if somewhat imperfect, initial version of Rust had been released by now, thus allowing it to gain some adoption and traction.
I hope that the "But Rust isn't targeting those developers!" argument isn't used to try to justify this mistake, as well. Rust is already facing stiff competition from languages like Go, C++11, C++14, Scala and even Java 8.
With the announcement of Swift, Rust's niche and audience are getting smaller, further preventing the widespread adoption that's necessary for a programming language to become truly successful.
We're not scared in the slightest. I'll reconsider when Swift has inline ASM, allocators, linear types, move semantics by default, region analysis, and a type system that guarantees freedom from data races (oh, and when the code is open-sourced, and targets both Linux and Windows as a first-class citizen).
Swift isn't intended to be a systems language: it's an application language. Anyone who's capable of choosing Swift as of today was just as capable of choosing Objective-C yesterday. And as the Rust developers themselves have discovered over the past two years, deciding to become a systems language doesn't happen overnight.
(In fact, on a personal note, I'm ecstatic that Swift has been announced. ADTs! Optional types! Pattern matching! Think of how many features are no longer alien to people who want to learn Rust! And hell, the syntax is incredibly similar as well, which further reduces friction. As a hardcore Rust contributor, I want to shake the hand of each and every one of Swift's designers.)
That said, Swift's types are a bit less than recursive, so there's a bit of niggling still before you get to the affordances of something like Haskell's `data`.
Also, even in systems, I can think of about once a decade I even need to write assembly, so... maybe grasping at straws a bit?
That said, I think inline assembler is an important feature:
> It's interesting that inline assembly is your first bullet point, since there's nothing I can think of that ruins a code file more than inline assembly in a host language. Put that crap in a .S file and link it in like everything else, for crying out loud.
That's too slow. You need to give the optimizer more information than that, and the overhead of the procedure call can be significant.
> The one time you need inline assembly is when you don't want to build a function frame, such as a tight loop, but come on.
But that's a very important use case.
> Also, even in systems, I can think of about once a decade I even need to write assembly, so... maybe grasping at straws a bit?
It's all over the place in the Linux kernel.
For Rust. I didn't make the comparison to Rust, I merely was intrigued by the choice of features and in which order to defend the comparison made by someone else. I see Rust and Swift as targeting entirely different things, at least at first (which means that Swift can certainly evolve inline assembly if it is so needed), and any comparison at this stage is pointless.
> It's all over the place in the Linux kernel.
Cool, that's one piece of software. I'll save you the next few: drivers and a couple files in a game engine. You're disputing my point how, exactly?
This is hilarious. Like anyone would ever use inline assembly in a tight loop.
That said, judging by your other comments, you seem to be of the impression that the Rust team has some sort of vendetta against Go, and have concocted a vendetta in kind. Again, I must sadly disappoint you, but I strive to encourage a culture of respect in all the forums that I visit (and moderate).
The last sentence of the comment to which you hint is my thesis. There is no subtext. It's easy to perceive negative opinions as attacks and create an adversary from the person writing the opinion, but it's also a little bit disingenuous. It also, conveniently, creates a platform upon which nobody can disagree with you lest they be hostile and aggressive. You can then exit on the "high ground," as you've done here.
I meant no ill will. Best of luck, I guess.
Perhaps this is news to you, but those of us who work on and are responsible for large-scale software systems tend to take such factors very seriously.
This may sound harsh, but it really doesn't matter what features and benefits Rust could potentially bring to the table if the lack of stability makes it unusable in practice today. A programming language that can't be seriously used might as well not even exist.
I don't doubt that Apple will have Swift available in a seriously usable form by this fall, and it's very likely that it will see rapid adoption soon after. I'm afraid I can't say the same about Rust and its supposed by-the-end-of-2014 1.0 release, given its current lack of stability and the rapidly-approaching end of the year.
1. Release fast and iterate
2. Release fast and be stuck with mistakes
3. Release slow
Option #1 breaks stability, so that's out.Swift appears to be taking option #2 (Apple doesn't commonly break APIs, do they?), but we can't even really be sure because it hasn't been developed in the open the way that Rust has. It's possible that it's been in development as long as Rust, and we simply haven't heard about it yet. Either way, option #2 is a perfectly reasonable one to go with; it has served Java quite well (for a loose definition of fast), though it has required some creative approaches to language improvements.
Rust is taking option #3. C has been around for over 40 years now. If Rust hopes to supplant it, it seems reasonable to take a few extra months (or even an extra year) to put out a solid version 1 that won't hamstring the language or force a breaking change down the line.
This is actually nice, because knowing about languages years before they are production ready probably just slows developer adoption because nobody is quite sure when they should trust there development process to a new language.
You also didn't realize that you just built the biggest strawman ever in the above sentence.
Enough with the "I want a stable Rust now". Rust, like any other language, takes years to stabilize. You just happen to see it happen in the open, whereas most other languages you get them at their 1.0 release.
>This may sound harsh, but it really doesn't matter what features and benefits Rust could potentially bring to the table if the lack of stability makes it unusable in practice today. A programming language that can't be seriously used might as well not even exist.
They could not give a flying duck about it being "seriously used today".
They'll start to care AFTER they release it as 1.0. They only released this 0.x versions to solicit ideas and improvements, not to get programmer's to adopt it.
Assuming this stabilization actually does happen, whether it happens in public or private is irrelevant.
What matters is that we've seen C++ stabilize. We've seen Go stabilize. We've seen Scala stabilize. And now we'll likely see Swift stabilize, well before Rust does. They are all serious competitors to Rust.
As these other languages continue to evolve, but at the same time remaining usable, the relevance of Rust will continually decrease. It may still have drawing power today. A few years from now, it will have less appeal.
If you like it, perhaps you should be a little patient and give the creators the benefit of the doubt. No one wants a Rust 3.0 fiasco.
It's hard to encounter language issues without implementing a large project in the language. I am happy that they're taking the time to let the implementation of Servo help inform the design of Rust.
It's hard to make a comparison against Swift, which is a proprietary language developed for years behind closed doors. Presumably they're at 1.0 from the first day by design. You can't do that with open source languages.
It's pretty absurd to expect Rust to be stable right from the get go. The difference in all this is that most of those languages were closed before being released. Rust was open at a pretty early state.
Personally, I consider the 0.1 release in January 2012 to mark Rust's "birthday". Everything prior to that was just gestation. :)
FWIW, Swift is categorized as a systems language in the opening pages. But, then, so does Go in its FAQ. To Swift's credit, at least it has deterministic memory management through ARC.
In general, reference counting has the problem that it needs to update the reference count. If you have a read-only data-structure these updates to the references will introduce writes that may severely impact performance since a write introduces cache consistency communication, while reads are communication-free.
It may not be ready as a systems language in its pre-1.0 form, but the Swift book claims that it's "designed to scale gracefully from ‘Hello World’ to an entire operating system", so Apple appears to have big goals.
Given Rust's PR, speaking of that -- not a thread about Go passes without at least three pcwalton comments these days -- I actually broke down and gave it a try. I wrote a little Hello World server and then got lambasted by a friend of mine for not working functionally, since, in his words, "Rust is a functional language and the fact that it supports other paradigms is a mistake." I rm -rf'd and ignore it for now, but I look forward to it stabilizing and maybe coming back to it.
Rust has potential but the PR needs to ease up just a little. There is room for more than one language in the world.
(small-time rust contributor here too)
Well, every thread about Go inevitably has numerous comments comparing it to Rust, often erroneously, and pcwalton is one of the primary Rust developers.
But as an industry, we need practical solutions that are available now, even if somewhat flawed. We need languages we can use today, and know that the code we write today will still compile fine next week and next year, if not a decade or more from now.
Modern C++ is getting pretty good at offering this, while offering far a greater degree of safety. Go isn't bad, either. Scala has its drawbacks, but it's often a reasonable option, too. The key thing to remember is that all of these languages have offered developers a stable target, and they are seriously usable in the present.
Given the announcement of Swift, and given that Apple will very likely deliver on it by the fall, we very well could see it becoming a major player during 2015.
The safety benefits that Rust could theoretically or potentially offer are virtually useless to huge swaths of the industry as long as the predictability of a stable release just isn't there. The longer this wait goes on, the better the competition becomes, and the less relevant Rust will unfortunately become in the long term.
By this logic we shouldn't invent any new programming languages at all. There's no such thing as a "practical solution that's available now"; everything takes time to develop.
> Modern C++ is getting pretty good at offering this, while offering far a greater degree of safety. Go isn't bad, either. Scala has its drawbacks, but it's often a reasonable option, too. The key thing to remember is that all of these languages have offered developers a stable target, and they are seriously usable in the present.
You aren't going to use those languages if you want memory safety without garbage collection. Because they can't offer zero-overhead memory safety without breaking existing code.
In other words, Rust is about safety with zero overhead over C++, and Swift is not zero-overhead. So the people who need Rust are not going to use Swift for Rust's domains. That's fine, as Apple wanted a language for iOS and Mac app development with tight integration with Objective-C, and from what I've seen they've done a great job of developing one.
> Things might have been different had a stable, even if somewhat imperfect, initial version of Rust had been released by now, thus allowing it to gain some adoption and traction.
Why are you so insistent that we freeze an unsafe version of a language that's designed for safety?
Pacabel has made a career of complaining about Rust being unstable.
I think that the recent, and very disruptive, ~ and box changes should completely dispel that notion.
I'm merely pointing out the reality of the current situation, which some in the Rust community do not wish to acknowledge, for whatever reason. The situation has yet to change, so what I'm saying is still valid, and will remain so until some actual improvement does take place.
Now that we see yet another serious competitor in the form of Swift, what I've had to unfortunately be saying for some time now becomes more and more relevant. If Rust is to become relevant, it will need to be usable, and that will need to happen very quickly.
No, he didn't say that anywhere.
To be crystal clear: no-one is suggesting that Rust is stable and no-one is suggesting it is ready for adoption (if they are, they are wrong). However, being unstable now is very very different to not ever being stable.
In any case, Swift is only tangentially a Rust competitor as kibwen demonstrated.
Rust is not stable, as you yourself have readily admitted. What I've unfortunately had to be pointing out for such a long time now is absolutely correct.
We've been told that we can expect Rust 1.0 by the end of the year. As each month passes, it becomes less and less likely that we will actually see this. We are still seeing significant change, even as recently as the past month.
I think Rust could potentially be very useful. But that requires stability, and that in turn is something that appears more and more elusive each day.
It's easy to say that Swift isn't a competitor to Rust, but the reality is that it is. And unlike Rust, it will very, very likely be usable for serious apps within a few months. It will see the adoption that Rust could have had, had it been usable, further reducing Rust's future changes.
All of those are highly uncontroversial and universally acknowledged by experienced Rust users.
Also, I don't understand how you have lept from Rust being unstable now, to Rust never being stable.
A 1.0 release by the end of the year doesn't seem at all unreasonable to me; I think you are expecting more from it than what the Rust team is looking for (and have stated publicly repeatedly): stabilising the core language.
Of course, a stable release of that form will still mean some libraries may be unstable (and so that Rust would be unsuitable for many corporate developments). These libraries will be stabilised progressively and iteratively.
No, he merely suggests that you bored a lot of people by repeating that it's unstable, instead of accepting the fact and using something else.
If being unstable is that bad, then by all means, go and use a stable language.
There are numerous alternatives to Rust that offer many of its benefits, but they're usable today. We can rely on them today, tomorrow, and likely for some time to come.
And by this fall, we'll likely have Swift as yet another option to add to our growing list.
I think Rust has a lot of potential. But each month that goes by squanders that potential. It has less and less of a chance of making a real impact the longer it isn't usable, especially while its competitors keep evolving.
Yeah, and I listen to Rihanna instead of Jay Farrar. Obviously that's the big problem Jay is facing, and he should sound more like Rihanna to cater to my taste.
The recent, and rather disruptive, box changes are a good example of this. We see change, and those of us with existing Rust code sure do feel the change, but very little convergence seems to be happening.
Based on past trends, I would not be at all surprised if problems are found with the new approach as it becomes more widely used, and some other approach is then attempted.
Wheel-spinning is something that can quite easily happen with ambitious software projects. It's not a new phenomenon. But when facing ever-increasing competition, and other real-world constraints, it's often better to aim slightly lower and at least be mostly usable in practice.
A memory-safe programming language that can't actually be used is pretty much irrelevant. It's better to accept some slight amount of imperfection if that means it can actually be used.
I believe it is, as the basic structure and rules of the borrow check (which is the part of Rust that's truly unique) have proven themselves to be quite usable. The usability problems remaining are implementation and precision (e.g. issue #6393), not big problems that will require large redesigns.
> The recent, and rather disruptive, box changes are a good example of this. We see change, and those of us with existing Rust code sure do feel the change, but very little convergence seems to be happening.
Yes, it is. The number of outstanding backwards incompatible language changes is decreasing. People who do Rust upgrades notice how the language is changing less and less.
> A memory-safe programming language that can't actually be used is pretty much irrelevant. It's better to accept some slight amount of imperfection if that means it can actually be used.
"Some slight amount of imperfection" means not memory-safe. Java didn't settle for that, C# didn't settle for that, Swift isn't settling for that, and we aren't settling for it.
At the end of the day, if Rust fails, well that will be a shame. But I'm seeing nothing that shows that it might, so I'm truly struggling to understand why you seem so upset by a new modern language trying to tackle big problems in ways that have never been done before. That's a good thing, as far as I'm concerned.
I bring this up again and again because I'd rather not see Rust fail. I'd much rather see a slightly flawed Rust that's actually usable in the short term, rather than a continually changing Rust that nobody will seriously adopt.
Rust has been in development for years now. That's a very long time in the software industry. A few years of development time without a stable release is understandable. But it's getting beyond that now.
Rust isn't quite there yet, but each day it edges closer to a Perl 6 type of disaster. Perl 6 offered some intriguing ideas, but it just isn't usable, and that's a shame. Meanwhile, other competitors have arisen and blown past it, rendering it far less useful were it ever properly implemented.
Given the increasingly stiff competition that Rust is facing, I suspect we'll see it end up like Haskell or D. Something usable is eventually produced, but it never sees the truly widespread adoption that it could have seen, had it been usable earlier on. It's not as bad as Perl 6's situation, but it is still unfortunate.
I don't have much to say about D, but the history of Haskell implied by this sentence is hilariously wrong.
Go watch Simon Peyton Jones' talk about the history of Haskell: http://research.microsoft.com/en-us/um/people/simonpj/papers.... As well as being wonderfully entertaining, it explains the actual history of Haskell: it was designed to be a language with which various academic groups could do functional programming language research. The fact that Haskell has gradually grown more popular and now has mainstream appeal and some industrial users is quite a surprise to its creators.
Not for programming languages. These take years and years. Take a stab at any of the most popular languages. They weren't created 1-3 years ago. It takes time, and that's a good thing.
The optional type stuff is good, and it will definitely be a net safety improvement, but it's by no means attempting to approach a panacea to safety like Rust's strict static analysis does.
Particularly that Swift gives you really simple outs in the form of the '!' unwrap and 'as' (should be 'as!' at least imo) downcast-and-unwrap operators that result in run-time errors and will probably be seen as unremoveable code-smell in a couple of years.
If the book is good documentation, then use it. But you may benefit from focusing more on problems than completing a book.
Honestly skimming 500 doesn't sound horribly hard to me. I've done that a few times to pick up something new. As ap said you won't learn the language like that but you will have a good reference to go and learn from after the fact.
After that you could probably work through the examples in said book, or at least the interesting ones.
P.S. above steps is all I really learnt from my cs degree.
Definitely take a look through it. You definitely don't need to be a language nerd to understand it.
Just as a point of fact, javascript -- at least the v8 implementation I'm most knowledgeable of -- doesn't "keep the entire context alive forever." Only variables used in the closure are allocated into the closure (i.e. on the heap), the others are allocated on the stack and disappear as soon as the function returns.
I don't use iTunes so can't read their book, but I wanted to ask: you say that ARC is still their GC strategy, correct? So reference cycles are still an issue? I'm surprised at this. I can see reference counting being a strategy for moving a non-GC'd language to GC (like Objective-C), but to start a new language with that constraint is surprising.
I'm not sure that's true. Look at the following code:
var x = 123;
var f = function(xname) {
eval('console.log('+xname+');');
}
f('x');
It's a dynamically named variable. Clearly, f() has access to the entire context that surrounds it, not just the objects explicitly used in the function code. In this example, the compiler could not possibly have known I was going to access x.This means in Javascript, as well as in Ruby, when you hand a closure to my code, I can access the entire environment of that closure.
Contrast that with Lua, for example, where the compiler does indeed check whether an outer variable is being used and then it imports that variable from the context only.
PHP does it most explicitly, forcing the developer to declare what outer objects they want to have available within the function.
The original assertion by curveship was that the outer context is not kept alive for the function, and that f() only gets access to the variables it explicitly imports from the outer context. And I thought this might be wrong, so I cooked up the example.
Again, this is not about scope. This is about the fact that the function itself keeps a reference to the entire context it was created in, as opposed to just the things it explicitly imports.
In this, it appears, Javascript works exactly as Ruby, which again makes the entire outer context available through the binding facility.
I'm sorry if that wasn't clear from my description.
Right, but it knew you were going to use eval, and to support that, it had to allocate all local variables in the closure. That's why you saw this behavior. The same would happen if you used a 'with' construct.
Wow, so there is actually special handling in the engine for this? So it does static analysis whenever it can, but not in these two cases?
function f() {var x = 99; return function(a,b) {return a(b)};}
f()(eval, 'console.log(x);')
ReferenceError: x is not defined
function f() {var x = 99; return function(a,b) {return eval(b)};}
f()(eval, 'console.log(x);')
99
undefinedSee here for an example: https://www.meteor.com/blog/2013/08/13/an-interesting-kind-o...
This bug is still not fixed. There's an issue open for it on the V8 tracker, I believe. It seems to have not gotten fixed in either engine because it's a difficult problem that affects a small subset of JS applications.
V8 has seen a lot of really nice optimizations to closures over the last year. My favorite is that closures are no longer considered megamorphic.
For me it looks like Scala + a sprinkle of C++14 :)
Jacob Leverich https://leverich.github.io/swiftislikescala/
Den Shabalin http://www.scribd.com/doc/227879724/Swift-vs-Scala-2-11
As an amatuer/hobbyist programmer who's self-taught with Ruby, JavaScript, etc., the one thing that was keeping me from experimenting with iOS apps was Objective-C. I know I could tackle it, but it's been hard to take the plunge.
I don't know much about Swift yet, but from what I've seen it looks very exciting. So if Apple's goal was to get new devs into the iOS world, at least from 10k feet, it's working.
I'm excited!
COBOL, Fortran, JCL (not Turing complete, AFAIK), SQL, Excel, DOS batch files all were (fairly) mainstream at some time.
[1] http://www.digibarn.com/collections/posters/tongues/Computer...
More importantly, "inspired by" does not imply that Fortran 58 is Algol-like (that same picture would declare Fortran Lisp-like, too)
For me, http://en.wikipedia.org/wiki/Fortran#Simple_FORTRAN_II_progr... certainly is nothing like Algol.
Perl and C++ are still in the lead, but with stuff like the gratuitous introduction of alternate hash syntax, new-style lambdas, etc., Ruby is catching up.
[1] http://stackoverflow.com/questions/23980929/what-changes-int...
It's definitely more exciting than something like an incremental update to the Apple TV.
Swift is shit. I suspect it will die in a couple years, like the misguided effort to get people to adopt the Java bridge or WebScript before that.
If you know one other language really well, Objective-C should take a week or two to get use to.
To understand all the design patters, apple HIG, XCode, profiling, libraries, debugging, app submission, etc, these combined is where youll sink your time to learn iOS development. Imo, Objective-C is the easy part.
I had 0 objective-C experience, but I made it work. It was a bit of a frustrating experience. Many times I found myself writing Objective-C boilerplate-ish code that I had 0 clue what it was doing, considering this is a hobby / for fun project I just wanted it working.
It's not easy to google the answer to, "Why did I just add this new keyword after this colon in this random .h file.."
I didn't want to spend the next month reading Objective-C for beginners, I know what a for loop is, I also know what constructors are. I just wanted to use the language.
The only thing that got in the way was the difficulty using the code away from OS X or iOS, and the fact that a lot of libraries for things like database access (especially those intended for iOS) were never intended to be used in a long running process. I found slow (3 week) memory leaks that someone writing an iOS app would never have hit.
I loved Smalltalk and I love Objective-C at a deep level. The Objective-C runtime is incredibly powerful and its method dispatch is astonishingly efficient considering what it does. It is not as fast as vtables, but it isn't as fragile either.
It might well interest you to know that WebObjects (I'm talking 1997 here) ran on HP-UX, SunOS, AIX, and one other popular Unix of the day that slips my mind and it too shipped with a lively scripting language called WebScript which was not so different from a minimal Swift today.
The thing is, once you dig into the Objective-C runtime and spend a bit of time trying to write an interpreter, you start to realize that the interpreter almost writes itself. Swift is far from the first language built atop the Objective-C runtime.
Consider FScript (http://www.fscript.org) has been around for well over a decade and does more or less the same thing except it gives you something closer to Smalltalk than Javascript and it includes some advanced matrix manipulation goodies as well.
The majority of the people squealing with glee over the introduction to Swift seem to be the sort of people I wouldn't care to work with. If a bit of syntax puts you off so much, lord help you when a truly new paradigm hits.
Swift looks to have some nice features, but it seems to be missing the low level access to the runtime that advanced developers can use like default message handlers (forwardInvocation:/doesNotUnderstand:/methodForSelector: kinds of stuff) and the ability to fiddle method dicts at runtime which can be very useful for intercepting strange errors and unexpected code paths.
So, yes, I do LOVE Objective-C. It is my second favorite language to work in after Smalltalk and to those claiming that Swift will help them move over from Android because it less verbose - lets remember Java is the most boilerplate per capability language I've seen since COBOL. I don't know what those people are talking about.
@lazy var asHTML: () -> String = {
[unowned self] in
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.lIf thzt sjunds like fun tj yju, thzn gj fjr Jboective-C.
[ ] does not mean method call, it is the syntax for a message send.
Objective-C is a super set of C, adding an Smalltalk like object system to C. The delimiters say "I am sending a message", which is different to a method call. Also, without them the language would be much more difficult to parse, and future changes to C could break the language. It's lasted well (first appeared in 1993). Not as long as Lisp, perhaps it needs more [ ] :)
1983, actually.
In Smalltalk and Objective-C, the target of a message is resolved at runtime, with the receiving object itself interpreting the message. ... A consequence of this is that the message-passing system has no type checking.
There have been a lot of C-based object-oriented APIs over the years. GObject has a C API. On the Mac, there's Core Foundation and a bunch of other OS X APIs that are built on top of it. For over a decade on X11, before gtk and Qt even existed, the closest thing there was to a standard graphical environment was Motif (the corresponding desktop environment was CDE), and Motif was built on top of Xt. Xt was yet another C-based object system, although it was specialized for designing UI components.
This is all well and good but you end up with a ton of boilerplate code that does nothing but manage the lifecycles of the object instances (retain/release for example), and lends itself to extremely verbose function calls in place of object methods.
One possible solution is to put together some really elaborate preprocessor macros to make it look like you have extended the C language to include special syntax for your object system, so you can at least replace this:
obj foo = obj_factory(); int c = obj_getNumberOfElements(foo);
...with something more compact like this:
obj foo = [Obj new]; int c = [foo numberOfElements];
(the second example is ObjC-ish but the former is nothing in particular other than just what the typical C object APIs tend to look like)
The only catch is that the little mini-language you are extending C with using macros can't use existing C syntax, because you can only add to the language, not alter the behavior of existing operators. So, you can't just do method calls using a dot syntax on the instance (such as foo.numberOfElements()). So, you have to come up with something new. Maybe you always liked Smalltalk, and maybe you even based much of behavior of your object system on how Smalltalk objects behave and interact? If so, you might settle on the bracket notation. This has the added benefit of making it very clear when a chunk of code is run-of-the-mill C versus when the code is triggering the syntactic sugar you created with macros to add support for your object system to the C language.
C++ doesn't exist yet, or else you might've just gone with that instead of rolling your own thing. Eventually C++ does exist, and you start to feel a little primitive for sticking with the weird macro language. You eventually build your mini-language into a C compiler so you don't have use the macros anymore. You experiment with some new alternatives to the syntax that are more conventional, but no one uses them. Many developers like that the non-C-ish syntax makes it easy to distinguish between straight C code vs. interactions with the object system, which has its own set of rules and conventions.
Anyway, that's mostly speculation, but something like that story is how I've always thought Objective-C evolved over the years. I don't mind it nearly as much as long as I don't think of it as a separate programming language from C (like C++ or Java or pretty much anything else these days), but rather think of it as C with some useful syntactic sugar that gets rid of a ton of boilerplate code for a particular C-based object-oriented API.
> So if Apple's goal was to get new devs into the iOS world, at least
> from 10k feet, it's working
They just announced Swift, at a conference for Apple developers, with live streaming that is only easily accessed from an ios device. I think it is probably premature to pop the corks and celebrate the efficacy of the get new developers initiative.Swift looks amazing and I'm really excited to try it out tonight! Great job Apple devs.
I dislike that Apple has continued the special snowflake approach, that for some reason we as developers need to learn yet another different-but-almost-the-same language to develop for them, instead of just adding proper support and documentation for an existing language. Why not just let us use ES6, or normal C/C++, or Java?
But instead, now there's yet another language without great innovation that is probably going to be badly supported outside of the Apple ecosystem but still will have enough fandom to keep it alive and make life annoying.
At least Google had the decency to pick a language everybody was already using and use that.
EDIT:
I feel bad for all the engineers stuck in those pixel mines, not allowed to talk about what they're doing, doomed to reinvent things that are on the way out just as they come in.
At least Microsoft and Google show off their new projects and code so everyone can learn from them and read their research.
Hint: one of these things is not like the other...see if you can figure out which using only the power of curl.
Frankly, a bit of a clean up every decade or two is not exactly often, right?
I really don't get why you can bring up languages such as Rust and Go, and complain about Apple's special snowflake approach. Suddenly Apple is doing something developers have been demanding from them for years and something lots of other companies like Google, Mozila and Microsoft has already done. But oh no, because it is Apple, it is all wrong.
And yet they've decided to do it again, with yet another incompatible language! Joy of joys!
(And as for Java, it was my understanding that Apple had hobbled it by refusing to release updates on a timely basis.)
I can see how they could get tired of being forced to ship almost-monthly updates just to support an extra language with very limited adoption. If you have to make that sort of effort, you'll probably do it for your native tools only (like Microsoft does with .Net). Besides, Java apps on OSX looked better than Java apps on Windows, but they were still recognizably different from Obj-C ones.
I wish somebody would write an OS in Python 3...
That's a different, later issue.
Early on in the life of OS X, Apple offered a Java interface to the Cocoa class frameworks. In theory, you could write OS X applications using Java, calling into the Apple frameworks instead of using Swing or whatever Java frameworks.
This wasn't all that well supported, didn't perform well, and wasn't popular.
The Java/Objective-C bridge existed in the early days as they weren't sure if developers would pick Objective-C, so they decided to bet on two horses.
As Objective-C eventually won the hearts of Mac OS X developers, the bridge was deprecated and a few years later the full Java support.
I've been amazed recently how many open-source projects that we rolled into our linux product were Apple sourced: LLVM, Clang, libdispatch, webkit, OpenCL, zeroConf. Can't think of anything google has done for me recently.
And if there is anyone who will knock-this out of the park, its Chris Lattner. LLVM, Clang, and openCL is all him. He has done more for compiler tech than anyone in 30 years.
If you think Java is remotely comparable in power and expressiveness to Objective C, you should probably reconsider your line of work.
The rise in popularity of Java nearly drove me from the industry it is such a verbose half baked pile of garbage. I could fill your browser with things you can do in Objective C that you cannot do in Java at all and this incredible flexibility is why Apple is such an agile company with such limited head count.
I'm not trying to troll, I just think that it's a pity that Apple tends to limit the ecosystem and applications of its otherwise-great languages. Building against LLVM ought to make it fairly trivial to make this cross-platform.
http://en.wikipedia.org/wiki/Apple_Computer,_Inc._v._Microso....
Let's not forget that webkit when it was released was little more then a code dump - one big patch that had to be applied to KHTML.
What Fortune 500 (or even 5000) systematically open sources every piece of technology? Every company I can think of -- Yahoo, Microsoft, Google, Facebook, LinkedIn, Twitter, Amazon, LinkedIn, AOL, Craigslist, Oracle, -- selectively decides what to open source.
I'm not saying that's right or wrong, but Apple is far from alone in doing so.
I've uploaded it just now
I'll get down voted for this, and it will be truly ironic.
Bring on the Downvotes!
https://developer.apple.com/library/prerelease/ios/documenta...
I assume you'd need a developer account, though.
It feels very lightweight, sort of like an analog to what Javascript is in a browser.
There are a few other languages that do this with the Obj-C runtime, for example a Lisp variant called Nu[0].
I see the standard static FP features (from ML, Haskell, Scala, F#) with the syntactic flavor or Rust and some C# tossed in.
This is a big shift. With such a rich type system (very Hindley-Milner .. even with "protocols" that feel like type classes?), there is no need for exceptions, for much the same reason that Haskell doesn't have exceptions in the core language, but only a monad. This would force error situations to be explicitly modeled in the types of objects returned by functions/methods. A good thing I think.
However, it does leave the hole of what if an ObjC framework you call on raises an exception? Can't handle it within Swift code? Another big omission in the manual is lack of mention of anything to do with concurrency, though "use GCD" is seen as the solution (Swift closures are compatible with ObjC blocks).
Haskell doesn't care about this stuff, because lazy evaluation gives you the same control-flow patterns, and the exception monad ends up operationally equivalent to checked exceptions, but now with possibly exception throwing values made first-class. I doubt the same can be said of Swift.
What I find more amazing is that, as humans, we have all chosen "5+ years" as the experience level in our jokes.
Unlike C and Objective-C, Swift enumeration members are not assigned a default integer value when they are created. In the CompassPoints example above, North, South, East and West do not implicitly equal 0, 1, 2 and 3. Instead, the different enumeration members are fully-fledged values in their own right, with an explicitly-defined type of CompassPoint.
+100 for that. This will help developer avoid whole class of bugs.
Enumerations also support associated values. Enums in .NET are very poorly defined. Looks like Swift got it right.
http://en.wikipedia.org/wiki/C++11#Strongly_typed_enumeratio...
Well that’s gonna make storing persistent values tricky.
Heck, they could have bought RubyMotion and made Ruby the high-level language of choice for development.
I realize that Apple has a long tradition of NIH ("not invented here"), and in many cases, it suits them, and their users, quite well. But there are so many languages out there already that it seems like a waste for Apple to create a new one. Just the overhead of developing the language, nurturing its ecosystem, and ensuring compatibility seems like it'll cost more time and money than would have been necessary if they had gone with an existing language.
Because OBVIOUSLY none of them solve the problems they wanted to solve (interoperabillity with Objective-C, fast, native, IDE integration, etc. Including RubyMotion which is a half-arsed implementation.
IDE integration for a new language? They wrote it themselves. Do you think it would have been harder to integrate an existing language? Fast & native also also trivially solvable.
I don't know about interop with Objective-C, that's probably the hardest part from your list.
But complaining about IDE integration when they're also the creators of the IDE is... silly...
Clang was easier to integrate with an IDE than GCC, and I strongly believe (after seeing what apple showed yesterday) that swift integration is even simpler.
( They must have made a new LLVM front-end to embrace IDEs equally or better than Clang )
So no, it's not silly to try to design better to have a better integration with an IDE that you control too.
Cheers.
Most (if not all) IDE's Ruby and Python integration is BS.
We're talking about real AST-based highlighting and suggestions, auto fixes, autocomplete for all APIs available (AND your own custom modules), integration with the debugger and the build system, and in Swift's case also integration with the REPL, LighTable-style live-variables and Brett-Victor-inspired live coding environment.
This is not your grandfather's PyCharm.
So, even if just adding IDE integration for an existing language was easier than creating a new one, using an existing language wouldn't solve their other issues (e.g Obj-C interoperabillity with message passing, protocols, named parameters et al). And RubyMotion wouldn't permit all the optimizations they did, nor the kind of type safety they added.
>But complaining about IDE integration when they're also the creators of the IDE is... silly...
We're not talking about PyCharm level of IDE integration here. Not even about the current level of Obj-C/C++ integration XCode offers (for which they had to create LLVM tooling and LLDB to enable all the features they wanted to offer). It goes beyond that.
Radical hypothesis: what if this started as a pet project, got the attention of more employees, then management (with or without convincing from said developers). Management sees the value in the project, and funds it officially. You know, like other big, rich corporations...such as Google.
Much more probable is that somebody asked top-developer Lattner for "a simpler language to compete with Java/Dalvik and C# with more casual developers" and he came up with Swift. The name itself is a message: "this thing is quick - quick to learn and quick to run, unlike VM-based stuff that must translate to Obj-C (fast to learn, slow to run) or Obj-C itself (fast to run, slow to learn)".
The iOS/OSX ecosystem is absolutely big enough to support an exclusive language (see Objective-C), and Apple chose to create a new language that matched their goals instead of adapt something they don't control and isn't ideal.
Makes perfect sense, and Swift was by far the most impactful announcement at WWDC.
Really, really interested and excited about learning Swift.
Direct link to Elm's demo similar to Bret's: http://debug.elm-lang.org/edit/Mario.elm (video: https://www.youtube.com/watch?v=RUeLd7T7Xi4)
The Future of Programming: http://bit.ly/1pNtKMh Inventing on Principle: http://bit.ly/1opRrJp
Apple knew there was Swift-Lang, and still called this Swift. At least they link to it from their website!
Sigh.
"The Swift parallel scripting language web is experiencing heavy load due to Apple's announcement of a new language by the same name. We'll have a raft of new web servers online shortly to handle this trafic. Please check back in a few hours! -- The Swift team..."
We'll have new web servers online shortly to handle this traffic.
Please check back in a few hours!
-- The Swift team..."
What a weird and pointless comparison, imo (I mean the inclusion of Python, seems so random to me).
It's supposed to be a "mainstream" scripting language. Also, it's an easy way for them to get favorable numbers for their presentation.
They probably just used python as an example of something most people would know. Its probably the most known scripting language out there so why not use it.
Besides ALL benchmarks are pointless, even when you have the source of the benchmarks and know what they ran on software/hardware wise.
http://forums.somethingawful.com/showthread.php?threadid=363...
"Is this under NDA?
No.
Is this open source?
Not yet. It probably will be, but I can't make promises. Right now, our repository still has a lot of history that we don't want to make public, and we have a lot of work to do before we release."
Of course, it's an easy target. But I can see why they went for it.
I guess the comparison with Python is that Swift code looks more like Python than C.
I would have been interested in a JavaScript comparison, which I'm sure we'll be seeing from third parties soon.
println("Hello")
I think the idea was that Swift will be as easy to code as Python and faster than Objective-C.There's no reason C#, Java, etc. can't have such things exposed, but they get so wrapped up in their boilerplate and OO overhead they choose not to.
On the superficial level, the use of line breaks to separate statement (although ; can also be used), on the deeper level the is an accent on accessibility and no non sense behaviour, where other language might have made more compromises on readability for instance.
(I can't find any references to it)
https://developer.apple.com/library/prerelease/ios/documenta...
It'd be great if someone could get the book, convert it to PDF and post it online.
ePub[1] has been posted elsewhere in this comment thread.
[1] https://news.ycombinator.com/item?id=7835994 (accidentally said PDF instead of epub before)
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer or device for personal use only and to print copies of documentation for personal use provided that the documentation contains Apple’s copyright notice.”
Edit: Seems to be working now anyways :).
In the intro of the book "The Swift Programming Language," which Apple just released on Itunes Book store, it says:
“Swift has been years in the making. Apple laid the foundation for Swift by advancing our existing compiler, debugger, and framework infrastructure. We simplified memory management with Automatic Reference Counting (ARC). Our framework stack, built on the solid base of Foundation and Cocoa, has been modernized and standardized throughout. Objective-C itself has evolved to support blocks, collection literals, and modules, enabling framework adoption of modern language technologies without disruption.”
Book is available here:
https://itunes.apple.com/us/book/swift-programming-language/...
[1] http://en.wikipedia.org/wiki/Objective-C#Popularization_thro...
However, GCC is not longer used by the Apple toolchain. They could easily close up their work on Clang and LLVM, and haven't. Further, they're obviously still contributing - they've recently added their ARM64 backend to LLVM.
The Apple software ecosystem isn't particularly closed. Much list iOS and OS X, they're based on a pretty open foundation, with proprietary libraries on top.
I have the same problem with using c#/.Net (outside of work), it isn't a language I want to use at home or want to deploy onto a server.
2) Hopefully this puts some pressure on Google to make Go on Android easy (although I'm a Java guy myself).
3) What about swift-lang (http://webcache.googleusercontent.com/search?q=cache%3Aswift...). It has the same name and almost the same icon. Did they work with these people or just screw them?
Look at the bottom of the page. There's a link to the swift-lang site...from an Apple web property. That's probably more publicity than the swift-lang folks could have hoped for in a million years.
So I took a moment to look at why Dylan was cancelled.[1] Veryin interesting stuff. What it came down to was:
- Apple was in dire financial straits
- Apple needed to axe all projects that didn't show commercial viability
- At the time, when Apple was transitioning to PowerPC, Dylan was 68K only, and needed another year or two to be ported
- Most damning, the project was not finished - it wasn't even in the optimization stage.
None of these factors are in play here. So. My worries are assuaged. I do want to learn this, and it looks really easy to pick up so far.I'm really curious now about two (unrelated) things:
1) is this good enough to build web apps with? 2) how would one manage the transition of an Obj-C based project to a Swift-based one? Assume I don't have the budget or manpower to perform a ground-up rewrite.
[1] http://en.wikipedia.org/wiki/History_of_the_Dylan_programmin...
Porting NSView subclasses first would give you a win, because if you use Swift the classes can draw themselves at design time in Interface Builder. (Objective-C view subclasses just draw a white rectangle in IB.)
1) How does Apple releasing Swift make you feel as an Objective-C developer?
2) Are you excited to code using Swift?
3) What about Swift makes you most excited?
4) Do you worry about upskilling to Swift?
5) How do you think Swift will change the way you work?
6) What concerns do you have about swift?
Keen to understand how this impacts people and share that if you have time to talk to me :)
If you don't want to email, just reply here.
For example:
var apples = 3; // mutable
let oranges = 5; // immutable
let summary = "I have \(apples) apples and \(oranges) oranges";
The string interpolation syntax is unique, but kind of makes since given then \ is the escape character in C strings.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
var distance:Double = 70.0
a. No fall through. This is a plus in avoiding bugs. This is minus if you really know what you are doing and want fall throughs b. Pattern Matching in case statements. This is bit interesting and should take care of the previous case.
Other than that my first impression is it's a mishmash of various programming languages. Everything else that they demo'ed seem to be features of XCode (rewinds, variable lifetype analysis etc..) rather than the language itself.
A bit of python looking stuff and some ruby looking stuff in there too. I am intrigued enough to give it a try when it is available.
EDIT: Nevermind, my mistake. I thought the comment was about Apple was making their own language like Google did with Go, not Go! already existing as a language
> Looking for the Swift parallel scripting language? Please visit http://swift-lang.org
http://kristofferr.com/files/The%20Swift%20Programming%20Lan...
The IDE they demoed looks very interesting on its own—it reminded me of Bret Victor's posts (http://worrydream.com/LearnableProgramming/). Immediate interactive code visualization, quite impressive.
Did they not know or do they just not care?
Also Swift-lang is Apache 2.0 licensed, which I have a feeling Apple wouldn't use as a base for a new language.
[1] https://trac.ci.uchicago.edu/swift/browser/branches/release-...
--Steve Jobs
Does this mean that we can use the Swift REPL in the Xcode debugger to explore running ObjC programs? That would be enormous fun, not to mention very powerful.
Having ARC and not needing GC will end up being a big fundamental advantage for its parallelism story. (The problem with GC, is that one thread does work, then a GC thread comes along and possibly causes an additional cache miss.)
Whoops. Should've corrected that when I copied the comment over.
In any case, reference counting is disastrous for the parallelism story. GC thread coming along and causing an additional cache miss is way better than having to do atomic operations on reference counts all the time.
Why are atomic reference counts necessary? You wouldn't generally need them with an Erlang-like Actor model or for special concurrency primitives like Go channels. (That is to say, you'd only need them in the special mechanisms.)
I'm managing something like this in Go. There are no refcounts, but everything is very much mutable. I'm basically arranging for a span of time where I know nothing unprotected by a channel is going to be mutated, then I simply let every thread in the app that cares to read data from every part of the heap, but only during this span of time. The same technique could be applied to a ref counted app. (It would probably work best for games that have a tick.)
I still think it would be hard to apply to a ref counter app, since you'd need to keep track of change in ref count for later cleanup (thread-local per object maybe? sounds inefficient), but I now will admit that it sounds possible.
It is probably not a good sign that it can be immediately compared to every modern (and not so modern) language in existence.
I really like that it is incorporating good parts of many, more terse languages. Nothing wrong with selectively absorbing good ideas.
But a huge part is the interactive nature. I dabbled in Smalltalk some years ago and have been annoyed at compiled languages ever since, resorting to things like http://injectionforxcode.com to gain some of that back (on iOS).
Having a live environment can only be appreciated once it has been taken away. I think developing for Apple devices might just become one of the more programming pleasant experiences.
Here is the link to the online documentation if you don't want to download it on iBooks.
Many web developers (like myself) have used Phonegap/Cordova in conjunction with tools like the Ionic Framework for our apps, primarily due to the nearly esoteric (for some of us) nature of Obj-C, but Swift almost looks like JS, which certainly has motivated me to learn it and use it in future apps.
I wonder if the aforementioned tools will lose market share because of that. Let's see.
Thinking about it a bit longer, is it because of the clear distinction between non nullable values ans optionals that the compiler can optimise the code so much more ? (I am thinking about the xx times faster than Objective C claims)
I see the value of the safeguard, but it seems cumbersome as a language level rule; I hated The boilerplating in Java, and it goes a bit in the same direction. I'm not sure I like the bureaucracy of explicitely testing every single variable that could be nillable to use them, but I'd love to be proven wrong.
In my opinion, having that as a language rule will probably force people to design their classes to have things set at initialization more often than not.
Good point. There are some interesting work in javascript, like Om, to mainly use immutable objects, it could go in the same direction.
> No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-branded products.
It is pretty closed, if you ask me. Legally binding a language to a specific brand of product is a new low.
- function-level type inference much like Rust
- no constness in the type-system (I like it)
- class are reference types, structs are values types, much like D and C#
- runtime dispacthed OO interfaces called "protocols". Blend the difference between runtime or compile-time polymorphism. Classes, structs and enums can implement a protocol. Available as first class runtime values, so the protocol dispatch will be slow like in Golang.
- enumerations are much like Ocaml ADT, can be parameterized by a tuple of values, value types, recursive definitions (nice)
- worrying focus on properties.
- strange closure syntax
- optional chaining, another anti-feature in my eyes
- normal arithmetic operator throws a trap on integer overflow (!). This must be incredibly slow.
- looks like Array is a fat slice to a reference-counted array
- operator overloading is in, supercharged with custom operators, custom precedence (!?)
- builtin tuples syntax
- break with C integer promotion, like Rust.
- no pointers
- convenience is a keyword!
- no exceptions (!)
- unsigned integers: check
- type inference is "bidirectional by expression or statement"
- classes have deterministic destructors, structs have no destructors
- It seems the only RAII source is through RC and classes.
- no single root class
Make your own opinion.
I am thrilled they did this. Implicit Overflow is the stupidest shit I know that everyone takes for granted.
Also with CPU support it could be free, and adds negligible complexity to the silicon.
> At the `-02` optimization level, our compiler prototype showed only a 5.58% slowdown when running the SPECINT2006 macro-benchmark. Although that percentage represents the worst-case performance for AIR integers (because no optimizations were performed), it is still low enough for typical applications to enable this feature in deployed systems.
Edit: The latest version of OS X does support iBooks. Lets hope you have that.
Looks like the end of the line for this particular bit of history: http://www.tikirobot.net/wp/2008/11/22/why-gcc-has-a-free-ob...
https://developer.apple.com/library/prerelease/ios/documenta...
Also some other useful stuff:
https://developer.apple.com/library/prerelease/ios/reference...
NOTE
For the best experience, open this chapter as a playground in Xcode.
Playgrounds allow you to edit the code listings and see the result immediately.
Downloading gives me https://developer.apple.com/library/prerelease/ios/documenta..., a zip file with about 50 html files, a .css, about 40 .swift files and two files Results.playgrounddata and contents.xcplaygroundDoes that mean that playgrounds can be used for literate programming?
If Apple wanted to add official support for a new language I would think it would have been a better move to use something that already has an established following and could potentially attract new developers over. Something like Ruby/Python/Lua would seem to fit the bill nicely.
We've already seen Ruby can be done successfully on Mac with MacRuby and RubyMotion, but it nevers get full support from Apple.
Adding an additional programming language that binds me only to Mac platforms doesn't give me a whole lot of incentive.
The runtime of Swift is also the runtime of Objective-C, but the runtime might need some upgrades to fully support the Swift semantics in a safe manner.
EDIT: Correction. It's available also on iOS 7. Just confirmed by Apple. Great :)
The video should be available on Apple's site (or if not, very shortly).
EDIT: Tested with 6.x and works.
-(void)addNumber:(NSNumber*)num withString:(NSString*)str;
How is this called in swift? Is it myobj.addNumber(42, withString:"Hello World")? -(void)addNumber:(NSNumber)num withString:(NSString)str;
to addNumber_withString(num, str)
Swift could be different, though.so if it has to be something, it might be myobj.addNumberWithString(42, "Hello world")
myobj.addNumber(42, withString:"Hello World")
edit: I see you removed your equals - your guess is now correct :)for more details, see this link on apple's docs (may change)
https://developer.apple.com/library/prerelease/ios/documenta...
UIColor *color = [UIColor colorWithRed:0.5 green:0.0 blue:0.5 alpha:1.0];
let color = UIColor(red: 0.5, green: 0.0, blue: 0.5, alpha: 1.0)
Wow, this just brings up more questions, is the compiler removing the "colorWith" semantics or do you write your own translator?They do explicitly state that initializers will get "init" and "initWith" stripped off and whatever follows becomes the first parameter. The fact that "colorWithRed" is translated to "red" might indicate that it is looking for the keyword "With"
... well I meant put it somewhere I could download from my Debian
Looking forward to the Lambda the Ultimate discussions on this new language.
- Porting to other platforms/community implementations (think Mono)
- Developer input: being able to submit bugs, influence or even just *watch* the trajectory of the language, get a deeper understanding of how various components are really implementedSwift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/il/jEUH0.l
You can still point to nil pointers and crash the program because of it, and you can still have retain cycles which creates memory leaks.
That language really looks more of trying to make good compromise rather than create a revolution or a breakthrough. In a way, that feels like a much safer choice.
I can say Swift takes inspiration and improves on at least these languages:
C:
typealias
struct
control structures
labeled statements AKA gotos
varargs
C++:
default arguments
class instance construction syntax
// comment
superclass, implementing protocol declaration syntax
semi-virtual class init, deinit
Go:
No parentheses around the condition part of control statements
Unicode identifiers
shorthand for signed and unsigned integer types U?Int(8|16|32|64)
C#:
in-out params
properties
subscript access of class member values
Objective-C:
ARC
protocols
extensions
param names as method names
willSet/didSet
nil?
Java:
enum
@final
super keyword
override method keyword
Scala:
Local type-inference, blend of an ML flavored FP with OOP without the noise and believe it or not, even more powerful in specifying generic type constraints. No stupid JVM type erasures either so you can actually create an instance of a generic type, just like C++ templates.
Self:
self
Python:
for i in enumerate(seq)
for key, value in dictionary
Type(value) explicit type conversion syntax
No public/private/protected class member access modifier bullshit
Array literals, dictionary is also like Python but use [] instead of {}
Ruby:
0..100, 100_000
Lisp:
closures
Scheme, Coffeescript:
? optional type modifier
Bash:
$0, $1... inside short callback closures
Innovations
---------------
break-less switch, optional fall-thru, comma as multiple case, case can be any value of any type, condition or a type constraint for pattern matching, supports method call shorthand
generic type constraint queries
overflow operators
@prefix, @postfix, @infix, @assignment modifiers for operator overloading Trailing closure as partial function application
Gripes
------
Seems like array[4..6] is even more useless than Javascript's Array#slice, and a far cry from Python's slices.
No set literals and list/set/dict comprehension.
Nothing for concurrency???? No yield, no generators, no channels, not even the synchronized keyword.
There's no decorator or annotations, and Swift isn't Objective-C, what's with the odd-ball @ modifiers?
I don't see namespaces as mentioned in the WWDC slides, and goto is definitely still here so you might just write another gotofail.
Looks like Swift is Apple's answer to Go, Rust, Scala, Java, PyObjC/RubyMotion, Unity, Xamarin and all these HTML5 + JS/Phonegap people. I'll definitely pay attention to Swift. If the performance results hold up, Swift + iOS8 will definitely leave Android's ancient Java 5 crap way out in the dust.
https://itunes.apple.com/us/book/swift-programming-language/...
Like Go and Dart?
dispatch_async(queue) { /* code here */}
That's an idiomatic adaptation to dispatch_async to support closures. I guess this internally might be converted to a block.
“if let actualNumber = possibleNumber.toInt() {
println("\(possibleNumber) value: \ (actualNumber)")
} else { println("\(possibleNumber) could not be converted to an integer")
}”Nice to see the Apple's language developers embracing functional programming by providing a clean implementation of the Maybe Monad as well as support for closures.
https://developer.apple.com/library/prerelease/ios/documenta...
if (x = proc()) {printf("%i", x);}let 🐶🐮 = "dogcow"
Moof!
For instance, the registered trademark symbol ® is just option+r. ∑ is option-w. Diacritics are two-stroke combinations, to get é, you'd type option-e, which puts the ´ on the screen, and then type the e to complete the character.
Some of them definitely make more sense than others. ∑ looks like a sideways 'W", the trademark symbol is just a circled r, and the diacritic marks fit the character you'd commonly associate them with. (Guess what letter you hit to get ¨ over a letter?)
Beats copy/pasting out of character map, anyways!
Sure, but even making your own keyboard layout beats copypasting out of character map for any characters that you use regularly (and if you switch from US-English to US-International as your base layout, you get a lot characters that aren't on US-English for free without making a new layout.)
And, after they ran out of mnemonics, they sprinkled the rest of the characters on the keyboard (almost; I think they tried hard to keep things memorable, but some combinations are just plain of the "if you don't know it, you 'll never guess". The Apple logo is on the k key, for instance (IIRC). Mnemonic? MaKintosh?)
"Diacritics are two-stroke combinations, to get é, you'd type option-e, which puts the ´ on the screen, and then type the e to complete the character."
That's the old way. Recent OS X has 'hold down the e key, a menu pops up, click the desired variant or type the digit shown next to it'.
On a more serious note, several languages have that, Ruby included.
I think we're approaching the level of unicode penetration that this shouldn't really be much of a problem.
Incidentally, I think this will be much more useful in Japan and possibly parts of China than in the parts of the world that speak an indo-european language (and therefore has an easier time learning English).
But, those areas that doesn't speak native English is of course just a small market. /s
func Polar(x complex128) (r, θ float64) {
return Abs(x), Phase(x)
}
It seems to be good for documentation reasons.Looking forward to it.
Edit : Changed the link to en.
Does anybody have a direct link to the Xcode 6 beta ? Or mirror download link ? Thanks.
Thanks for the direct link!
Interestingly enough, the time manipulation in Swift was inspired by a game called Braid (http://en.wikipedia.org/wiki/Braid_(video_game)) released back in 2009.
This will help young programmers solidify the connection between giving the computer logical commands and what is outputted on the screen immediately.
Reminds me of how excited I was when Processing (http://www.processing.org/) was released which made it dead simple to interact with a screen and graphics. Didn't have live feedback, but it made it incredible easy to understand OOP.
Setting up a dev environment can be one of the big reasons people fail to learn to program.
1. Buy particularly expensive computer 2. Register as an apple developer 3. Install Xcode, and you're ready to go.
> Setting up a dev environment can be one of the big reasons people fail to learn to program.
Citation needed :)
1. Buy a Mac mini for $600, which doesn't strike me as particularly expensive.
2. There is no step 2.
3. Download Xcode from the Mac App Store for free.
Trouble was, teaching the entire XCode and Objective C tool chain was not a particularly easy entry point for learning how to develop programs.
(Maybe there were other prerequisite programs, but still, you need to understand C to really understand why a lot of things are the way they are in Objective C, in addition to message passing and object orientation, pointers, and other quirky stuff in order to really wrap your head around iOS development.)
Swift and the corresponding tools look like they would have been a godsend for teaching that class. A more practical way to get students started writing programs they can actually run on their phone.
http://www.lambdacs.com/debugger/debugger.html
But it never took off, for some reason. And it didn't have the arresting graphical aspect.
Bret Victor worked at Apple for a time as well.
It could, if it were open and not limited to iOS/OSX.
It seems any error messages aren't visible by default. Xcode shows a red "!" disc next to the line, and that's it.
The usual shortcuts for "Jump to next/previous issue" are disabled. Opening the issues tab with command-4 works, but it's empty. Apparently I have to mouse over and click on the tiny red disc to see any error message at all, and then it displays as text that can't be selected or copied.
EDIT: ctrl-command-M turns "Show all issues" on or off. It seems to be a little buggy, which may be why it's off by default. Hopefully we'll get the ability to copy the error text in the next refresh.
> Alternatively, remove a key-value pair from a dictionary with the removeValueForKey method.
Is that the day where an Objective-C got to choose method names? Why not dict.delete() or similar?
I’m not a one-character variable name type of person, but this makes my fingers (and my brain) ache, and for me makes the code harder to comprehend (wood for the trees, I guess, or something like that)
I can't tell if Apple is proposing this as a great new language everyone should use, or whether it's only intended for developers using Apple hardware and so represents a sort of lock-in strategy. I don't have an opinion on the language itself - it seems to have several neat features that make it easier/safer than competing languages like js, but presumably there are a few shortcomings as well.
As it is now I won't be able to use Swift because of that :(
I'd skip Objective-C and learn Swift to actually make a thing.
If you want general language knowledge, a really hairy production language and toolset isn't the place to look. You'll be fighting with lots of incidental stuff along the way.
Learning different kinds of languages will help you learn more languages.
- Optionals (Java's @Nullable)
- Tupples
- Functions as first class citizens
- let vs var (immutable vs mutable)
- Operators are functions
- Closures
- Extensions (Adding things to an existing class)
- Value object (struct - are passed by value -- and so are Strings!!! )
- Reference Objects (class)
- Generics (lets hope it will be better than Java's version)
- External Parameters ??
- @final keyword (to prevent overrides - like Java's final)
It kinda looks like C# meets Ruby meets the let keyword Very complex...
And More
- object reference operator === and !==
- typealias (~ typdef)
- Optional Binding (if let x = y.f() { } else {}
- for-in loops (for i in 0...count)
- The default behavior of switch is not to fallthrough
Using ARC removes control from the programmer and has a significant runtime overhead (atomic reference counts), which violates Rust's zero-overhead principle. What Swift works well when you need deep Objective-C integration, of course.
It's crazy how Apple is always so scared to release dev tools, at the end it will be out-there on bittorrent anyway...
Swift's way is arguably more sensible: the longer operator makes a longer range. But switching the way two similar-looking operators work, as opposed to at least two other languages popular with the target audience, is bound to lead to errors as programmers switch contexts.
Just the fact of having the two operators in the language together is dangerous, since they look similar and switching them will lead to weird bugs instead of immediate compile-time or runtime errors. Switching their meanings makes this more pernicious.
Time to prime our eyeballs to look out for this one.
[1] Swift book: “Use .. to make a range that omits its upper value, and use ... to make a range that includes both values.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
[2] Ruby: "Ranges constructed using .. run from the beginning to the end inclusively. Those created using ... exclude the end value." [http://www.ruby-doc.org/core-2.1.2/Range.html]
[3] CoffeeScript: "With two dots (3..6), the range is inclusive (3, 4, 5, 6); with three dots (3...6), the range excludes the end (3, 4, 5)".
func makeIncrementer() -> (Int -> Int)
EDIT: Why the downvotes? was just an observation not a criticism. Looking forward to using it instead of Objective-C.
how would you create a json deserializer ( which conveniently deserialized into NSArray and NSDictionnary of anything ) ? I didn't see any "object" or "id" type equivalent.
The Swift eBook is available at http://book.swiftlang.eu
What would you like to see there beyond reference docs, guides and examples?
Why doesn't Apple try to make easier to learn and easier to use programming languages instead of focus on the more difficult ones like Objective-C?
Why not use BASIC, Python, Ruby on Rails, Java, or even Pascal for their new language so you get more people to become developers and make iOS and OSX apps in greater numbers because it is easier?
I mean they could have just used Monodevelop: http://monodevelop.com/
Made a tool to convert Winforms to Cocoa Forms to port some Visual Studio C# and Visual BASIC apps to iOS and OSX, and win over the Windows-Only developers to the Apple platforms?
This Swift language seems so hard to learn, almost like F# or something. Not as hard as Haskell, but for the average developer it is going to be painful to learn.
Book Link: https://itunes.apple.com/us/book/the-swift-programming-langu...
Swift is a new programming language for creating iOS and OS X apps.
Swift builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works.
This book provides:
- A tour of the language.
- A detailed guide delving into each language feature.
- A formal reference for the language.
Hope it helps.
Playground is interesting.
Swift: a language for parallel scripting, 2011, mostly from University of Chicago
Anyone knows if it's related?
Edit: Canadian link worked! Sorry Apple.
https://itunes.apple.com/ca/book/swift-programming-language/...
https://itunes.apple.com/us/book/swift-programming-language/...
basically you just need to scroll to the bottom of the bookstore front page and touch your username to logout and then log back in.
https://developer.apple.com/library/prerelease/ios/documenta...
`NSJSONSerialization` worked pretty well with iOS 5.x and above.
Not sure if you're looking direct JSON -> Object serialization.
https://developer.apple.com/library/prerelease/ios/documenta...
Python and Ruby are resource profligate dynamic languages in comparison to other dynamics langs like Lua and Smalltalk. If you are surprised that someone could come up with a benchmark that disadvantages Python by a factor of 200, then you have a lot of neat reading to look forward to in language implementation and Python internals. For some reason speed is easy for our reptilian brains to grasp at. It's not the be-all end-all of a language.
Python's pretty slow.
Meanwhile, there is the Swift eBook at http://book.swiftlang.eu
Tuples and pattern matching are the bread and butter in Erlang and deserve to be mentioned as one of the source of inspiration for the Swift language.
The '_' character used to ignore some values in loops/patterns was also taken from Erlang (for _ in array { ... }).
If Apple's intent is to boost their developer base, this is one tremendous boost. It seems to have the best of both dynamic and static languages.
I did it because the book was free.
i.e.
enum BinaryTree = { case Leaf(Int) case Node(BinaryTree, BinaryTree) }
God, I love Apple. Now I just wish real innovative languages could market themselves as efficient.
If you are short on money, you can try to buy a second hand iMac or a MacMini (just be sure it will support the next OS X version 10.10).
The guides/reference link doesn't work yet...
It's like a scripting language very much. Quite amazing isn't it?
> Using the high-performance LLVM compiler, Swift code is transformed into optimized native code, tuned to get the most out of modern Mac, iPhone, and iPad hardware.
Coming from a Ruby background I couldn't be more surprised and excited!
func funcName() -> Int -> String { return { (i: Int) -> String in return i.toString() } }
Kind of looks like they took their logo too. LOL
Release versions of Xcode are freely available at no cost (except that you need a Mac)
In other news, has Android killed iOS yet so we can stop worrying about Apple? Can't happen soon enough.
The only reason I can see is vendor lock-in.
But you still need to type curly braces. Which are utterly redundant with indentation, pain to type, brainless task that languages should take care of, and a source of bugs.
Edit: You then have to click "OS X Yosemite Developer Preview". Then scroll down, it's at the bottom of the page
And all I thought was: "Please let it be a Lisp".
Lol
[ ] functional [X] imperative [X] object-oriented [X] procedural [X] stack-based
[ ] "multi-paradigm" [ ] lazy [ ] eager [X] statically-typed [ ] dynamically-typed
[ ] pure [X] impure [ ] non-hygienic [ ] visual [ ] beginner-friendly
[ ] non-programmer-friendly [ ] completely incomprehensible
programming language. Your language will not work. Here is why it will not work.
You appear to believe that:
[X] Syntax is what makes programming difficult
[ ] Garbage collection is free [ ] Computers have infinite memory
[ ] Nobody really needs:
[X] concurrency [ ] a REPL [ ] debugger support [ ] IDE support [ ] I/O
[X] to interact with code not written in your language
[ ] The entire world speaks 7-bit ASCII[X] Scaling up to large software projects will be easy
[X] Convincing programmers to adopt a new language will be easy
[X] Convincing programmers to adopt a language-specific IDE will be easy
[ ] Programmers love writing lots of boilerplate
[ ] Specifying behaviors as "undefined" means that programmers won't rely on them
[ ] "Spooky action at a distance" makes programming more fun
Unfortunately, your language (has/lacks):
[ ] comprehensible syntax [ ] semicolons [ ] significant whitespace [ ] macros
[X] implicit type conversion [ ] explicit casting [ ] type inference
[ ] goto [ ] exceptions [ ] closures [X] tail recursion [ ] coroutines
[ ] reflection [X] subtyping [X] multiple inheritance [ ] operator overloading
[X] algebraic datatypes [ ] recursive types [ ] polymorphic types
[X] covariant array typing [ ] monads [ ] dependent types
[ ] infix operators [ ] nested comments [ ] multi-line strings [ ] regexes
[ ] call-by-value [ ] call-by-name [ ] call-by-reference [ ] call-cc
The following philosophical objections apply:
[ ] Programmers should not need to understand category theory to write "Hello, World!"
[ ] Programmers should not develop RSI from writing "Hello, World!"
[ ] The most significant program written in your language is its own compiler
[X] The most significant program written in your language isn't even its own compiler
[X] No language spec
[X] "The implementation is the spec"
[X] The implementation is closed-source [ ] covered by patents [ ] not owned by you
[X] Your type system is unsound [ ] Your language cannot be unambiguously parsed [ ] a proof of same is attached
[ ] invoking this proof crashes the compiler
[X] The name of your language makes it impossible to find on Google[ ] Interpreted languages will never be as fast as C
[ ] Compiled languages will never be "extensible"
[ ] Writing a compiler that understands English is AI-complete
[ ] Your language relies on an optimization which has never been shown possible
[ ] There are less than 100 programmers on Earth smart enough to use your language
[ ] ____________________________ takes exponential time
[ ] ____________________________ is known to be undecidable
Your implementation has the following flaws:
[ ] CPUs do not work that way
[ ] RAM does not work that way
[ ] VMs do not work that way
[ ] Compilers do not work that way
[ ] Compilers cannot work that way
[ ] Shift-reduce conflicts in parsing seem to be resolved using rand()
[ ] You require the compiler to be present at runtime
[ ] You require the language runtime to be present at compile-time
[ ] Your compiler errors are completely inscrutable
[ ] Dangerous behavior is only a warning
[ ] The compiler crashes if you look at it funny
[ ] The VM crashes if you look at it funny
[ ] You don't seem to understand basic optimization techniques
[ ] You don't seem to understand basic systems programming
[ ] You don't seem to understand pointers
[ ] You don't seem to understand functions
Additionally, your marketing has the following problems:
[X] Unsupported claims of increased productivity
[X] Unsupported claims of greater "ease of use"
[ ] Obviously rigged benchmarks
[ ] Graphics, simulation, or crypto benchmarks where your code just calls
handwritten assembly through your FFI
[ ] String-processing benchmarks where you just call PCRE
[ ] Matrix-math benchmarks where you just call BLAS
[ ] Noone really believes that your language is faster than: [ ] assembly [ ] C [ ] FORTRAN [ ] Java [ ] Ruby [ ] Prolog
[ ] Rejection of orthodox programming-language theory without justification[ ] Rejection of orthodox systems programming without justification
[ ] Rejection of orthodox algorithmic theory without justification
[ ] Rejection of basic computer science without justification
Taking the wider ecosystem into account, I would like to note that:
[ ] Your complex sample code would be one line in: _______________________
[ ] We already have an unsafe imperative language
[X] We already have a safe imperative OO language
[ ] We already have a safe statically-typed eager functional language
[ ] You have reinvented Lisp but worse
[ ] You have reinvented Javascript but worse
[X] You have reinvented Java but worse
[ ] You have reinvented C++ but worse
[ ] You have reinvented PHP but worse
[ ] You have reinvented PHP better, but that's still no justification
[ ] You have reinvented Brainfuck but non-ironically
In conclusion, this is what I think of you:
[X] You have some interesting ideas, but this won't fly.
[ ] This is a bad language, and you should feel bad for inventing it.
[ ] Programming in this language is an adequate punishment for inventing it.
- it's not just an arbitrary language, it's the new officially sanctioned programming interface for Apple's gigantic, wildly profitable ecosystem
- it's much more concise than Objective-C
- it's faster than Objective-C
- it's safer than Objective-C
- it has more features than Objective-C
- ...yet it's fully compatible with Objective-C and C code running alongside in the same app.
And last, but not least, if you know how Apple works, you know that somewhere in the range of WWDC 2016-2018, Craig Federighi will be on stage, showing a pie chart and saying "Over 92% of developers have ported their apps to Swift, so screw the other 8%, we're discontinuing Objective-C".
Moving fast and constant change is the name of the game at Apple.
It makes good press release and marketing speak, but those assertions are a long way from making the OP 'wrong'.
And then you take another where you have no null pointers, no direct pointer access, and no possibility for array and buffer overflows (Swift).
And you say "nah, I look at these two, and I can't objectively tell which is safer"? Are you fuckin' kidding me?
Regarding speed, it's been proven faster by benchmarks, and by the fact the very reason Swift doesn't mix C types and Objective-C types is so the compiler can better reason and optimize the resulting code.
Swift was announced just a few hours ago. While we can make assumptions about its safety based on its feature set, or we can assume that the very vague performance details Apple provided are valid in a real-world setting, none of this has really been tested or verified independently yet.
What cratermoon wrote is perfectly legitimate. Let's try Swift out in the real world, perhaps for a year or two. Let's get some real data. Then let's analyze that actual data, rather than engaging in unsubstantiated speculation, or trusting some vague performance graphs shown in a conference presentation.
While you may not be aware with recent language development and modern LLVM-based languages in general, to me and many others what was announced at WWDC today wasn't just a set of buzzwords and marketing speak.
Anyone who has been into language design and watched the keynote today can make a pretty good guess about the properties of Swift. There's a book with hundreds of pages of examples and description of the language semantics on iBooks right now. I've been reading it before I posted. I've been playing with the beta Xcode as well.
Swift is not revolutionary in terms of its feature set. But what makes it quite interesting is the fact this is now an official language for Apple app development, and it's quite a bit ahead of Objective-C in... yes. Safety, performance and conciseness. Fact.
You may not have been around to experience it first-hand, but we heard a lot of claims made back in the 1990s about how Java and the JVM would increase security and safety.
The arguments made then even overlap with some of those being made in this case! The lack of direct pointer access and manipulation, automated memory management and better bounds checking are some examples of the arguments used then and now.
Yet if you work with computers at all, I'm sure you'd know that many of those claims did not materialize. Flaws have been found in the various implementations of Java and its VM, and these have affected its security and safety in very serious and significant ways, many times over.
Perhaps things are different in the case of Swift. But we won't be able to say for sure until later on, once it has undergone some significant real-world use.
You really should stop talking.
I'm saying that such features alone do not actually guarantee safety, if the language's implementation happens to have flaws.
There hasn't been sufficient time and opportunity to see what Swift is like in practice. It's premature to say anything conclusive about it at this point, aside from stating that we don't yet have enough information about it.
Writing in Java still remains monumentally harder to fuck up in compared to writing all your code in C or C++.
Furthermore, while Java relies on said relatively complicated interpreter + JIT virtual machine for its execution, Swift has no such virtual machine. All code is analyzed statically and compiled to machine code. The Objective-C runtime which it uses (which is not new - it's the same fucking Objective-C runtime) is a tiny C library, which implements a few basic low-level routines, such as dynamic message-to-method resolution.
So next time it's best for you to shut your mouth if you're ignorant about an issue, than telling people who know better than you to "wait for conclusive evidence".
[1] Oracle's JIT implemented in Java, from the meta-circular JVM Maxime
Giant step backwards. Vtables? I don't think so.
override keywords? WTF? Its not so much they removed the C as the "Object".
Lisp is relatively more concise than C or Java for the same tasks.
Java is relatively safer than C for the same tasks.
Lines of code is an objective measure. How meaningful that might actually be, well, that's subjective.
I'm not sarcastic or anything by the way, I just don't understand yet the foundation behind that statement.
First of all, while you can't do this:
case val:
case val:
case val:
...
You can do this in Swift, which does the same thing: case val, val, val:
...
Second, you can fall through in Swift, but you need to ask for it: case val:
...
fallthrough
case val:
...
So don't be sad.And third... Seriously now, it's a "very powerful programming concept"? I bet 9 times out of 10 you use this very powerful programming concept in other languages, you did it by accident, not because you needed its pawa.
ObjC was exceptionally type-unsafe. Any object type could be implicitly converted to and from the `id` type:
NSString* foo = @"hello world!";
id bar = foo; // no warning
NSDictionary* baz = foo; // no warning
The Foundation collections all used `id` for the values and keys when they had keys. `NSDictionary` will accept any object as a key, even though it will only work if the key is copiable and hashable, and it does mean that you could have keys of fundamentally different types in the same collection. Values can be heterogeneous too.As far as type safety goes, Swift is on par with modern languages.
ObjC also inherited several security issues of the C language, like unchecked arrays and unchecked arithmetic. Swift performs bounds checking by default (you can manipulate raw arrays with `UnsafePointer<T>`) and has checked arithmetic by default (you can allow overflows by prefixing the operator with `&`, so `&*`, `&+`, etc). It also never requires you to allocate and deallocate buffers yourself.
So Swift is more secure because it has no buffer overflows, no integer overflows (though they're more an issue when you have buffer overflows) and no unsafe memory management. These are by far the three most commonly exploited vulnerabilities in software.
-UnsafeButWarn compiler options -> replaces safe versions of arithmetic / arrays with unsafe ones, but issue runtime warnings whenever unsafe behaviour has occurred. Meant for debugging the runtime into never going unsafe, such that checks can be disabled.
-Unsafe compiler option -> replaces safe operations with unsafe ones. Meant for the production version that has been extensively tested but needs to run as fast as possible.
This is an advanced but powerful feature and is in fact exactly what Dr Alan Kay meant when he coined the term "Object Oriented". Any system that has abstract data types that does not have a default message handling capability is not actually "Object Oriented" and the "type safety" brigade strikes me as a bit like depression era prohibitionists. They can't handle it so nobody should have it.
The "type safety" thing is a myth. I have worked on colossally sized systems written in PERL/Mason, PHP, Ruby, Smalltalk, Java, and C++. You'll note that all but the last two are "type unsafe" by your definition and yet I think my last "type related" error was sometime around 2003.
Also, not all collections are meant to be homogeneous.
>ObjC also inherited several security issues of the C language, like unchecked arrays
Objective C developers use NSArray and NSString. Raw arrays and pointers to raw memory are beyond exceptionally rare in Objective C. This is just more prohibitionist propaganda. In the cases where there really are raw memory accesses - you need them - but for the most part Objective C provided safe alternatives and were used heavily (NSData for instance rather than raw arrays and NSString instead of arrays of char).
Nobody is going to do audio or video processing in Swift. The CoreAudio team used C/C++ because when you need performance, you need performance and bounds checking is inefficient.
I heard this sermon from the C++ people in 1992, and then the Java people in 1998 - there's nothing new here and the myth of "type safety" vs "type unsafe" still isn't really true. It is just a lot of baggage and lost capability we are being sold here.
Raw C is potentially unsafe. Objective C - not so much. You can write quite a lot without even using a pointer (apart from id - a safe dynamically typed pointer).
It's really nice to have the compiler not allow callers to pass null to functions where passing null wouldn't make sense, isn't useful, or the programmer was just too lazy to implement null checks. More than half of the functions I write have inputs where null wouldn't have an obvious meaning.
Objective-C's treatment of nil receivers is particularly handy for programming in the small and particularly bad for programming in the large. Sending a message to nil (similar to calling a method on null in many other languages) does nothing other than returning 0 cast to the type of variable you're storing the return value in. Chugging along accidentally accumulating nulls in many cases is worse than segfaulting and giving a nice stack trace.
Certainly in the realm of automated trading software, segfaulting when hitting a programming error is preferable to most other failure modes. Of course, failing to compile is often (though not always) the best failure mode.
2) UIApplication.sharedApplication.delegate vs UIApplication.sharedApplication().delegate - nope. It isn’t more concise. It appears to be a wee bit more verbose.
3) Some benchmarks on the web are saying otherwise. It adds extra bridging and ARC for numbers. I don’t see how it can be faster and even if it is - nobody cares about speed. If I need to beat it, I can drop to C, IMP cache, and kick Swifts sorry little ass.
4) Safer - like the TSA says flying without nail clipp ers is safer? It doesn’t solve any problems I actually have. I think my last type error was in 2005 - took about a minute and a half to find it. I routinely work in dynamically typed languages and avoid static typed languages like the plague they are. I’m not opposed to type annotations when they help, but these just look like cargo cultism - like a lot Swift’s silly “features”.
5) It has less features where it counts - basically a less capable object model, weaker meta model, and more budensome interaction with C code than Objective C and a number of useful Objective C features have been walled off. I have Objective C code that cannot be written in Swift.
6) Except for that kind of dynamic stuff like performSelector: afterDelay: withArguments: and that pesky NSInvocation that isn’t available.
There are better projects around than this pile of crap. I will not be porting anything. Quite a lot of code I have can’t be ported.
Java killed WebObjects. Lets not let Swift kill Cocoa.
This lame Usenet joke was a way of punching down at people joining language newsgroups trying to get people to pay attention to their half-baked language ideas. This, on the other hand, is a language that was introduced on stage at WWDC by Chris Lattner. You can see how especially clumsy the joke is by the fact that you checked off a reason Swift "wasn't going to fly". Obviously, it's going to "fly" just fine on the Mac and in iOS.
I hope you remember that when someone tells you something like 'it doesn't work here' that it's an opinion rather than a fact, regardless of how they phrase it.
The USENET era, while sometimes dated, was probably one of times in 'geek' history where we were the closest to one another. The internet was interpersonal, and i'm glad that someone is still trying to propagate the humor and spirit from that time.
First, it demonstrates how programming languages have been making the same tradeoffs for years, to the point that someone was able to make a checklist of what's wrong with any programming language that still works years later.
Second, you can fill this out for any of the big programming languages and many will do very badly. It shows how whether a programming language succeeds is unrelated to how good it is. An actually accurate checklist would have one item:
You're programming language will succeed because:
[X] It is tied to a popular platform.
With a graph showing ObjC at 127x faster than Python, Swift 220x faster than Python.
Thus the conclusion is 220 - 127, Swift is 93x faster than ObjC.
Someone needs to resit their GCSEs.
300x improvement instantly by moving it out of the loop.
I think it was covered by "naive memory management" and "shitty outsourcing". I'm paid to fix their stuff.
Another shrub in the walled garden!
Is that tongue in cheek? It's not even a particularly large, encumbered language, C.
A good example is the liberal use of the @ character to denote ObjC literals – even in front of strings and numbers, because raw C strings/numbers have different semantics and won't play well with the standard ObjC APIs.
This would make a lot more sense if you knew about the history behind Objective-C.
If that isn't enough, how about goto fail? All the IIS exploits in v4/5? Various Windows RPC overflows, WMF overflows, SQL Slammer, et al? How many billions in damages have been caused by stack smashing and buffer overflows? How many millions of hours of manpower wasted cleaning up after these errors? Toyota killed some people because their dumb code overwrote memory, blasting the OS task tables causing the watchdog task to stop getting CPU time, meaning nothing provided a stopgap against unintended acceleration. People are literally dying because we can't fucking let go of C.
C is like saying "forget seat belts, child seats, anti-lock breaks, and adaptive steering! How can I power-slide? I want full control; I need to pump the breaks. People should just drive better, then we'd have fewer accidents".
We've been trying to "drive better" for decades (Valgrind, lint, code reviews, static analysis tools, education, ASLR, NX protection, et al). We still regularly see massive security-smashing epic failures.
It hasn't worked. Furthermore the C standard library has been proven turing-complete for ROP gadgets in the presence of a buffer overflow. So no matter what you do, the presence of a single stack smash is enough to allow code execution, subject to payload size limits and execution time.
At some point we have to admit C is no longer acceptable. Not for libraries, not for drivers, not for operating systems. It has to go.
All the performance benefits ever derived from writing everything in C has been more than erased, by orders of magnitude, by the damage caused from even simple innocent mistakes.
Software allows us as programmers to greatly magnify our impact on the world; we like to think of that in positive ways. But the inverse is also true: thanks to the continued use of non-memory-safe languages we have the power to negatively affect the world on a massive scale.
It is unethical to continue writing code in non-memory-safe C or C-based languages, for any purpose. Period.
I'm looking forward to seeing your new operating system and managed runtime written entirely using garbage-collected languages!
There is still a large amount of change happening to the language and to the standard libraries. Some of this change has been of a here-and-there nature, where it's like they're trying to find an optimal or perfect solution that most likely does not exist.
C++11 (and C++14) may not offer the level of safety that Rust potentially could, but unlike Rust it's usable today, and using modern techniques does a reasonable job of avoiding dangerous situations.
It's been claimed that Rust will have stabilized and 1.0 will be released before the end of the year. Given that we're already into June, this becomes more and more doubtful each day. Now Rust is facing even more competition with this announcement of Swift. The longer we're forced to wait for a stable, seriously-usable release of Rust, the less viable Rust will become.
The reason why I put so much effort into Rust is because people who need to write the software in this space have literally no alternative that is not unsafe. Even if they cared about safety, they're screwed! Say that they need to write a library that can be written once and called from any language. That means, effectively, that they need to write that library in a language that 1) can expose a C-compatible interface, and 2) can run without a runtime. Which means, practically, that their choices of programming language are either 1) C or 2) C++. Despite Heartbleed, nobody's rushing to rewrite OpenSSL in ML. And I sure hope nobody's rushing to rewrite it in Rust either (we have no idea yet how Rust would fare for crypto, and we need time to figure that out). But once Rust is ready, you will at least have a choice. Memory safety will no longer be something that you leave on the table out of necessity.
I feel like the vast majority of the new programming languages coming out these days were conceived to make programming more pleasurable for the programmer. And yeah, I'm a programmer too, and I dislike many of the languages that I am forced to use every day. But Rust isn't about making programmers happy (although it seems to do that entirely by accident); it's about making users safer. Fewer vulnerabilities, fewer angles of attack for the baddies to exploit. And hey, if it makes software crash less, I guess that's cool too.
Not in the coming years, but it eventually will become a legacy language like RPG is, confined to old boxes running on long term maintenance contracts.
All is needed are a few mainstream OS where those languages are no longer part of the standard SDK. Like for example Microsoft just did with C as of Windows 8. Even their latest C99 compatibility changes were only done as they are required by C++11/14, nothing else.
> I feel like the vast majority of the new programming languages coming out these days were conceived to make programming more pleasurable for the programmer.
This was already possible with Lisp, Smaltalk, Mesa/Cedar, Modula-2, back when C was created, but then AT&T had better relationship with universities than Xerox PARC and ETHZ did.
And since memory-safe languages are written in non-memory-safe languages (i.e. C and C++), writing code in them is unethical as well, right?
Do you just put on your idealist hat and say, "Sorry! I can't develop a medical device for you. You'll just have to die. At least no one was required to be careful about their programming."
Some will say Rust, but we're years away from that being realistic. C++, using modern techniques, is perhaps the only feasible response.
While there may be some validity to your claim about "billions of human beings wasting hours" due to vulnerabilities in C code, we can't forget that the alternatives would also suffer from significant forms of waste.
If using a language with slower runtime performance, for example, people will need to wait longer for their computations to complete. More powerful, or even just more, hardware will be needed to alleviate these delays. Slower runtime performance also often results in much higher energy consumption. The costs just keep adding up and up.
Forcing billions of people to use far less efficient software, while requiring far more powerful hardware, on a continual and ongoing basis, for decade upon decade, could very well generate waste that far, far exceeds that of dealing with an occasional flaw in widely-used C code. I just can't seriously buy your "All the performance benefits ever derived from writing everything in C has been more than erased, by orders of magnitude, by the damage caused from even simple innocent mistakes." argument.
C won't be going anywhere until somebody provides a practical alternative that offers benefits without any downsides. It's as simple as that.
C is almost dead on Android, with its minimal exposure on the NDK and I hope Google does not change its mind about it.
C is now being killed on MacOS X and I look forward to Swift's success.
So this leaves out the embedded industry (slowly moving to Ada and Java on IoT) and the hardcore UNIX guys.
You can write shit code in any language - even Swift.
>how about goto fail?
I haven’t seen a goto in 20+ years. Strawman much?
>C is like saying "forget seat belts, child seats, anti-lock breaks, and adaptive steering! How can I power-slide? I want full control; I need to pump the breaks. People should just drive better, then we'd have fewer accidents”.
Yeah, and I suppose you’d prefer lumberjacks use rubber axes so they wouldn’t hurt themselves - or the trees for that matter. Life is dangerous. Get over it.
>At some point we have to admit C is no longer acceptable.
You bubble wrap your kids and lobby for lower jungle gyms at your kids schools too?
Swift doesn’t solve these problems and you sound like a self righteous ninny.
But hey - thats why there are scripting languages - for people who can’t deal with the machine. Pick one and go for it - but your scripting language isn’t suitably performant for things like audio processing (CoreAudio is in C/C++), real time control with tight tolerances, etc.
Grow the fuck up.
Sometimes you have to get your hands dirty and think hard and make stuff work. Your Swift code isn’t actually “safer” in the same way that the TSA hasn’t made flying safer - it is all security theater.
Personal attacks are not allowed on Hacker News. Please don't post anything like this.
Please. Please. PLEASE don't be whitespace delimited!
> x = 1; y = 2; z = x + y
=> 3But still, there's not a lot to hate. It looks like a cleaner javascript at first glance. Not quite as pretty as Python but then, what is. :)
One of the prime examples I give for how HN/reddit has gone downhill was being downvoted by some clueless hipsters for suggesting that it would be easy to cross-compile from a whitespace-delimited language to a non-whitespace-delimited one. It's not some kind of huge fundamental divide in languages. For any non-whitespace delimited context free language, it should be possible to write a homomorphic transformation to a whitespace delimited one.
This is something that people should consider trivial and be beyond discussing.
That said, whoever downvoted you for that reaffirms my belief that HN should have limited metamoderation with some kind of exponential backoff of mod privileges for egregiously poor moderation.
It makes me sad that companies are coming up with their own language stacks. Obviously Google vis a vis Oracle makes it a good move, if a company has the scale to accomplish and maintain it. Not to be a downer on what seems like a nice language, but other than that reason I see no need for Swift.
Syntax is not the most important thing in a language but it's not nothing either.
Should be doable as an editor plugin.
I'm not a fan of whitespace delimiting or type inferencing because while they seems like they save you time and effort, I've found that in the long run you end up spending more time debugging your indentations here or type declarations there than you would have spent just explicitly declaring them in the first place.
Note that your contextual value of "save time and reduce hassle" is mostly programmer dependent.
Edit: I pointed this out as I'm curious about trademark/logo clash.
As an extremely paranoid & defensive Javascript developer, you shut your damn mouth!! :p /jokes
Apple: To download Apple Inc.’s 'The Swift Programming Language', you need to have iTunes.
Me: What?
Apple: Using a 64-bit edition of Windows? On a Mac?
Me: No.
That experience just killed a potential programmer for you right there, Apple.
I had a few hours to kill, and was pumped to jump on the next apple cash cow and help us both, but you literally killed my ability to download the manual or learn anything more about it for a few days, by which time I'll probably be onto something else.
They have this: https://developer.apple.com/library/prerelease/ios/reference... But it doesn't look nearly as in depth as the ebook would be.
But thank you!