Hacker News new | past | comments | ask | show | jobs | submit login
Is Apple Using Swift? (medium.com/ryanolsonk)
142 points by ingve on Jan 18, 2016 | hide | past | favorite | 129 comments



A little backstory - I was working at Apple on the team that helped bring Swift to life.

The big roadblock (especially for things like frameworks) is 32-bit support. There's no 32-bit runtime for Swift. When that requirement is lifted I'm certain we'll see a flood of Apple apps built with Swift. There was (and still is) a huge amount of enthusiasm for the language internally. Many teams were working with it and plenty of internal tools where built with it. So yes, Apple is absolutely using Swift.


So how do Swift apps work on 32-bit hardware like iPhone 5/4s if there is no 32-bit runtime?


There's no support for the 32 bit OSX runtime. The 32 bit iOS is similar to the 64 bit iOS/OSX runtime and works fine.


Swift code is binary compatible with obj-c and xcode embeds a small Swift runtime library shim into your application for prior versions.

https://developer.apple.com/swift/blog/?id=2

But I really haven't tried it myself so someone else who has may be able to help you.


What makes you think they do?


The fact that I'm writing Swift apps, releasing them to App Store and testing those apps on iPhone 5/4s and having zero problems with that?


The "32 bit Runtime" is a misnomer. Its a difference between the modern and legacy runtime. iOS (and iPhoneOS) never supported the legacy runtime.

The name comes from it being the only runtime for 32 bit OSX apps.

https://developer.apple.com/library/mac/documentation/Cocoa/...


the legacy runtime before the `non-fragile` one?


1) I can run a Swift game on iPhone 5 which is still 32-bit.

2) http://stackoverflow.com/questions/24009876/how-can-use-cgfl...


> There's no 32-bit runtime for Swift. When that requirement is lifted...

You probably don't know/can't say, but is there going to be a 32-bit Mac runtime? Apple has spent zero resources improving the 32-bit ObjC runtime over the last decade, to the point where it's called the "legacy" runtime yet is still supported.

I expect a 32-bit Swift runtime would also require a modern ObjC runtime, but it seems rather unlike Apple to spend any resources now on 32-bit Mac (when they've decided not to for the last 9 years). I suspect that WWDC this June will be the beginning of the end for 32-bit Mac apps.


Given Mac has been 64-bit for a long time now, why would Apple support 32-bit?

I'm curious about your use-case, actually. Presumably you're not targeting non-64-bit Macs. So are you using 32-bit for better memory use? In that case, maybe Apple should introduce a 32-bit-pointer-on-x64 ABI, like Linux's X32.


No idea! Sorry man.


Let's hope we can get some delegates in AppKit that use weak instead of assign at the same time ;)


Craig Federighi (Apple's SVP of software) discussed this topic on this episode of the talk show (https://daringfireball.net/thetalkshow/2015/12/14/ep-139) a few weeks ago.

IIRC many teams within apple are using swift as much as they can, either for app/framework code, or test code. one example he gave was that the dock in El Capitan had been rewritten in swift. He also mentioned that the lack of 32 bit support for swift was a major pain point blocking more widespread adoption internally due to many frameworks still needing to support 32 bit macs.

Reading between the lines, it wouldn't surprise me if 32 bit support is dropped with the next version of OSX to allow more teams with Apple to start using no swift.


Mac OS X has been 64-but only for some time now. The last 32-bit Mac shipped almost a decade ago.


The 32 bit runtime (commonly used but misleading name, it should be called legacy) is still supported, but it's not compatible with Swift. iOS had the modern runtime from the start, way before 64 bit.

https://developer.apple.com/library/mac/documentation/Cocoa/...


It might be useful to look at Microsoft and their history with C#. C# was announced in 2000, the first really useful version C# 2.0 came out in 2005 and even today Microsoft apps written in pure C# are few and far in between (just UIs for visual studio, sql server etc.). So, I wouldn't be surprised if the Apple to transition to Swift doesn't happen for five years or more. There is absolutely no point for Microsoft or Apple to use C# or Swift when 95% of their legacy code is another language like C/C++/Objective-C. These guys have so much money they can pay people to hyper specialize in old technologies, I'm sure MS has some guys who work exclusively in COM/C++ or Apple with some guys who work exclusively in C89/BSD.

Having said that, pretty much everyone developing for the Microsoft ecosystem (native) uses C#. That has been true for almost a decade now. I suspect the same will happen with Swift and Apple and rather rapidly because the Apple ecosystem doesn't have enterprise customers holding it back. Most of people commenting here seem to already know Objective-C. However, consider someone new to the platform. Would you spend 1 year learning iOS programming using Obj-C or learn it via Swift? Apart from Swift being a nicer language to learn, the reality is almost all tutorials/books etc have shifted to Swift. Good luck to the poor sap learning iOS programming via iOS 6 tutorials and Obj-C and migrating to iOS 9.

I think the Swift 1.0 to 2.0 journey was quite painful, pretty surprised that Apple made so many breaking changes with poor tools support, but I feel 2.0 is where it feels just about solid to build all new apps. Sure there will be changes, I mean Obj-C had ARC and blocks twenty years later! but that's the nature of software nowadays.


I think the difference here is that C# (and the .NET platform) was never meant to completely replace C/C++ Win32 development; it was a higher-level solution for a certain class of Windows applications.

I might be wrong, but I thought Swift was designed as an eventual replacement for Objective-C (with its seamless interoperability, and the fact that it uses the same runtime as Objective-C, it doesn't seem that far-fetched). If it is meant to be Objective-C's successor, then Apple should really be preaching by example at this point.


> I think the difference here is that C# (and the .NET platform) was never meant to completely replace C/C++ Win32 development

Oh no, it was meant to replace them. Win32 was going to be deprecated, all new stuff would be on native .NET APIs, there'd be a Windows Presentation Foundation and a Windows Filesystem and it'd all be great.

The thing is that Longhorn fell apart, and with it the dream of replacing Win32 died forever.

Now we have WinRT, but unlike the plans for Longhorn, WinRT actually sits on top of Win32.


Right! Longhorn; totally forgot about that and WinFS. Talk about a failed endeavour...

WinRT however is definitely not a replacement for Win32. It's way too sandboxy (last time I checked, you couldn't even pull up a list of fonts installed on the host system using the WinRT APIs only).


Most of the new software MS has been developing over the past few years - the Azure platform, office 365, etc. - is server side. I suspect a significant quantity of that code is managed.


I'd like to know how much .NET code is in Microsoft's products now. I would have expected plenty in Office, Windows 10 and Edge, but I don't know how to actually check.


> Dumpbin /clrheader <binary file>

This will report the .NET runtime version for any CLR binary.


Until there is some stabilization of the language and its main libraries/ABI (coming in v3.0 or so), I don't think the language can really take off. The changes can possibly break it, is it really worth it to invest in something that next year will change breaking your code?

From Swift v3 on we should start seeing things going!


They provide tools to port. So I think it depends more on how large your app is. For a small app running the tool and making a few misc fixes will probably be fairly easy. At least if it is like the 1.0 -> 2.0 change.

For larger apps, well, I have a Swift app that isn't really very big, probably still small but significantly bigger than a tutorial, and it keeps freezing Xcode. (Edit something in Interface Builder, switch to the ViewController class with IBOutlets in it, then switch back and forth between ViewControllers making edits. Each time it takes longer and longer until I just force-quit Xcode to avoid twiddling my thumbs for 5 minutes.) So I don't think Swift is ready for any app that isn't pretty small anyway.


It's pretty naive to think that Apple would somehow direct all their work towards re-writing existing code into Swift. There is literally no use case to do that wholesale.

Firstly, there is no question that it would generate bugs. Appkit and even iOS is old enough that you couldn't replace it completely without the behaviour changing. Even if it's fixing a weird behaviour, that would be a problem for many existing apps build on that framework.

Second of all, it would mean they wouldn't be moving forward with new features, which, basically nobody (customers even) wants.

I'm sure more and more new code will be Swift, and possibly non-framework apps can be re-written. But they won't start announcing a swap out in the next WWDC.


Also, the number of developers required to rewrite everything in Swift on a short timeframe is likely more than Apple has.


There's one massive use case: to demonstrate to developers that it's advantageous and ready for prime-time.


That statement demonstrates a rather naiive understanding of the software development life cycle. As well as how successful businesses in general behave.


Wrong on both counts.


...how exactly? Companies shouldn't and don't waste time rewriting things for no reason, just to use a new language.

Swift is already production ready and Apple has plenty of examples, beyond that there's nothing to "prove".


I don't think that use case is so massive.


Also, attracting and retaining talent. Talented devs are only going to stay interested in writing ObjC for so long.


It is hard and costly to rewrite an app, even for Apple. In this case it means learning new skills (or hiring new devs). This is huge and will probably take years to be adopted. They could also force it at some point by releasing new APIs with only Swift support.

It's worrying for Swift. If it really adds value compared to Objective-c then why is Apple so slow on jumping on the bandwagon? They need to show the way. Other companies usually talk with their fans through dev blog posts but Apple secrecy tradition and very tightly controlled communication does not help.


https://developer.apple.com/swift/blog/, or any Swift developer twitter account, really...

Everything surrounding Swift has been the most open Apple has been in a very long time

Edit: https://swift.org/blog (the current blog)


Yes thanks. This looks more like a documentation than a blog. I meant there is nothing more personal like here is how we migrated our app x to Swift (real world examples) with:

- What was challenging ?

- Lessons learned

- Performance measured before/after

- In general what was the gain ? Why should I bother except for the hype ?


I think the gain is mostly that Swift allows you write code which more resistant to bugs than its ObjC counterpart would be.

In Yaron Minsky's "Effective ML" talk, he mentions the idea of "Make illegal states unrepresentable": https://vimeo.com/14313378

The combination of enums and non-optional variables allows you to get much closer to this ideal than you could with ObjC.

A great place to start would be the Functional Swift talks from 2014 and 2015: http://2014.funswiftconf.com/ http://2015.funswiftconf.com/

If you want to challenge yourself, try reading through the RxSwift codebase: https://github.com/ReactiveX/RxSwift


When I interviewed at Apple I talked about Objective-C vs Swift with multiple developers. Most seemed to indicate that due to the millions of lines of code already written in Objective-C that they, at least personally, were highly unlikely to rewrite them in Swift because it currently works and it's not worth the change over from a product standpoint. In fact a couple of time seemed hesitant that Swift was the future when I talked to them about it.

I understand not wanting to rewrite millions of lines of code but I feel like they should at least want to make a slow transition of at least many of their apps to Swift (since it can bind with Objective-C it's not like it has to be done all at once; it could be something where they spend a small percentage of time doing off and on). After my interview though I got the impression, at least from the developers I talked to, that they will probably never use Swift unless they have to.

Edit: I would like to point out, in case it's not obvious, that my case is purely anecdotal. Reading responses here and searching around Google is seems many inside Apple are excited about it which could very well be more than the people not excited about it. Still, I'd like to see some more platform support as it appears small at least to me looking from the outside.


One would assume that their own people are already quite experienced in Objective C, and there is little benefit to them in switching to Swift. As long as Apple keeps supporting Objective C, why should the people already proficient in it change? It just isn't practical.

However, Swift is invaluable in attracting new developers who are unlikely to take up Objective C.


I don't like Swift and I like Objective C much more. I learned Swift, so I can read it, but I'll use Objective C whenever I can. May be there are more people out there with similar point of view.


Yeah as nice as Swift is, Cocoa was designed for Objective-C.

e.g. -[NSBezierPath setLineDash:count:phase:] takes a C array in Objective-C, but an UnsafePointer<CGFloat> in Swift.

Apple needs new API interfaces for their new language, and that will take time.


If you use this API very often from Swift you can introduce nice wrapper around it. It would be better to see these issues by Apple but I think they are minor and Swift overweights with its benefits.


This will improve in Swift 3.0, via an improved mapping of Cocoa APIs into Swift (naming wise):

https://github.com/apple/swift-evolution/blob/master/proposa...

At some point in the future I imagine we would also see native Swift APIs.


We tried using Swift for a new app but the language isn't ready for prime time. It's an impressive language by itself, but the support for it just isn't there yet. Since it's still in infancy things change too much and documentation/stackoverflow is pretty weak. Our app was simple but we spent more time trying to make it work than actually programming and ended up doing an obj-c rewrite in less time. I'm sure this scenario won't be the case for long, but it's the case for now.


I wrote an iOS app around the iOS9 release and did it purely in Swift. It's a great language and easy to grasp. I liked the if let pattern for example.

The hard part is using the frameworks and not getting annoyed of XCode slow downs, the language itself is very friendly.

Documentation is good too. Worked through the Stanford course which gives you a great introduction and a book about iOS design with Swift implementation.


I would be interested to hear what didn't fit your needs. So far there are some performance issues with containers as value types. Other bottlenecks are structs that contain many references types.

Is there anything in particular you can point to, I'd love to take a look.


For reference, it would be prudent to review the swift-evolution Github repo:

* Swift 3.0 goals[1] -- 3.0 is scheduled for late 2016 and it will bring a wealth of ABI and language stability improvements, and significant documentation improvements

* Commonly rejected changes[2] -- significant whitespace, "and" keyword vs && (et al), closure literals, and semicolon removal are not on the table and that doesn't seem to be changing anytime soon

Swift is great and all but it will probably not reach critical mass until 2018.

[1] https://github.com/apple/swift-evolution#development-major-v...

[2] https://github.com/apple/swift-evolution/blob/master/commonl...


I think this somewhat addresses the issue, at least from Federighi's perspective:

https://medium.com/@Klehmann79/see-https-daringfireball-net-...


Agreed. Federighi and his team are seasoned vets in building and delivering software to millions.

They aren't naive and know they need to balance end-user benefit with engineering's wishes for maintainability etc. Is the user going to see a vast difference in experience if they re-wrote the Settings.app? Swift is a language, not framework, so it doesn't offer the end-user anything worth caring about.

Swift will probably cost them more than it gains them in the immediate term, but the long-term is what Apple is all about, so I don't think they are concerned about this.


Obviously the sane approach is to write new code in Swift, including tooling and tests (as in Federighi's example). Not to rewrite and possibly breaks apps that are shipped to millions of users, just because of ideological reasons. Any software engineer who has worked on complex projects should understand this, no?


"Swift has quickly gained popularity among many third party developers"

Where Swift has really gained traction is with bloggers and book authors. I past 3000 urls in my Swift Resources database over the weekend. I wrote this blog last night:

https://h4labs.wordpress.com/2016/01/18/3000-swift-urls/

Here's a direct link to the resources: http://www.h4labs.com/dev/ios/swift.html


Slightly related : like many Android engineers, I fell in love with Kotlin. It is a very pragmatic language which solves many big issues with java 6.5 we use on mobile.

However, getting it adopted in a big project with a dozen of engineers of various levels and a massive 300k LOC repo is a daunting task.

Even though it is a undoubtedly a better language, making such a switch is too frightening for the lead dev. Of course, Kotlin has the additional disadvantage of not being officially sponsored by Google on Android.


If you want to retain compatibility with legacy code, use Xtend (http://xtend-lang.org), which compiles down to Java 5.


Kotlin is already entirely interop with java : it compiles to bytecode compatible with jvm 6.

The problem is an unwillingness to switch to a new language ("we do just fine with java") coupled with the fact that ideally everyone in the team should get familiar with it.


> "we do just fine with java"

Yeah, except they write 2-5 times more code in Java, than they would in Kotlin. I think it's unprofessional to reject a new language, that will make code smaller and easier to understand, just because somebody is afraid to step out of his comfort zone for a moment, and not because of some potential real problems.

I think you can justify anything with that stupid line of thinking: "I don't use for-loops, because a while-loop can do the same, and it's too hard for me to learn it." Sounds the same to me. Learning Kotlin is a must for any Android developer, unless he really likes to give handjobs to the Java compiler: "Oh, let my type the name of the type twice, even if it's quite long for clarity and you know it already from the right hand of the assignment. You want me to write 23 lines of boilerplate in a separate file for a POJO with 2 fields? Oh, you dirty boy!"


>I don't use for-loops, because a while-loop can do the same, and it's too hard for me to learn.

Pretty much. Older engineer. He remembers the transition from blackberry to Android and is not ready for another one. He almost advocates for the use of Vectors ...

Unfortunately he is also Lead Engineer, which makes matters complicated. Kotlin is far from the only subject where we butt heads. I also had to put his nose on all the leaks created by his atrocious 'architecture' in order to start working on a fix.

I don't think there is a good solution for that kind of problems other than throwing the towel and move to another company. I plan to emigrate anyway, so there is that.

There are true reasons to avoid Kotlin at the moment though :

-slower compilation (we have a huge codebase and dexing is already an issue).

-the whole team needs to move to it and since we are more than a dozen, it is a significant task.

-Kotlin does not support Android Lint, so common issues like using an API 21 method with minApiLvl = 17 can occur unnoticed.


Compiling to Java code > compiling to bytecode. With Xtend, you get much better Java interop due to using exactly the same type system and you can use all the goodness of the original Javac.


I'm curious how exactly the OP can tell whether an app uses Swift, e.g., what command-line program is able to give that info.


Heres a list of the top 100 apps and what language they use. https://medium.com/@ryanolsonk/are-the-top-apps-using-swift-...

Generally you can tell from the downloaded ipa files. Apple is also allowing devs to delete default apps on iOS now - meaning they can also be sourced from the app store and you can check their ipa.


>> "Apple is also allowing devs to delete default apps on iOS now"

I hadn't heard about this. Do you mean I can delete things like the Stocks app? If so, how?



Interesting. Bit hacky but hopefully this leads to them actually introducing the option as a simple on/off switch setting.


Looking at the symbols using something like `nm` should make it clear. Swift mangles symbol names to include the module name and allow for nesting, and ObjC does not.


I would not be surprised if the percentage of Apple's code that is in Swift is more or less the same percentage of Google's code using Golang (with Golang having a slight advantage maturity wise). I'm sure Dart is even less. Of course this is just anecdotal from talking with a few people from Google so I'm probably off. That being said C++ has a huge advantage in that it keeps improving where as Objective C from my ignorant understanding has little plans of being improved (google has a large C++ codebase).


I would not be surprised if the percentage of Apple's code that is in Swift is more or less the same percentage of Google's code using Golang (with Golang having a slight advantage maturity wise).

That could be true, but what it's being used for is perhaps more important than the percentage. Not to underestimate the importance of a calculator, but it is known that Google uses Go in:

- dl.google.com

- Kubernetes

- Youtube's MySQL scaling infrastructure (Vitess)

- Google's mobile data compression proxy (Flywheel)

Of course, Go's first stable release was in 2012, so Swift still has some time to catch up ;).


Google uses Kubernetes? I thought it was just inspired by Borg and a 20% project.


I was under the impression that they intend on moving everything over to Kubernetes, in massive multi-thousand-host clusters.

Granted, the last I heard they had trouble scaling it up to hundreds of hosts, but there it is.


They are offering it as a service on Google Cloud Platform.


That's not quite true – Apple has added quite a few improvements to ObjC over the past few years. Not sure if this has slowed down since the introduction of Swift, but I presume they will still keep coming for now, since (as this article postulates), Apples still mainly uses ObjC internally.


That's true, but arguably, the changes introduced into Objective-C (ARC, properties) were to support a future compatibility with Swift. The fact that it simplified Objective-C was probably a bonus.


Jetbrains seems to be dogfooding pretty good with kotlin.


I have to imagine JVM interop is substantially easier than the ABI route but I'm not an expert in that area (that is it substantially easier to call legacy code and probably port). I do like Kotlin though.


Im not sure why Apple would just arbitrarily re-write proven code because there is a new language. This makes no sense. Should a technical/business case arise to rewrite something, then sure do it in Swift. Is there some subtext here that he is trying to prove that apple doesnt believe in their own language?


Why rewrite code if it isn't broken?


Shows dedication to the platform.

Currently, Swift is being hurt by incompatible changes between 1.x and 2.x. There are expected more incompatible changes between 2.x and 3.x.

If Apple had significant investment in Swift apps, they would not be making breaking changes so lightly. Because they don't, breaking changes are expected and why should be you the one, who is constantly rewriting the app you have?

TL;DR: it hurts the adoption of the language.


>Shows dedication to the platform.

You generally want to show dedication to a platform with sane means. Not by writing multi-million line codebases, and creating new bugs, cut-down features and delays in the process (a la FCPX, which was in the same language as 7, but still a total rewrite).

>If Apple had significant investment in Swift apps, they would not be making breaking changes so lightly.

And the language wouldn't have fixed its early mistakes and matured. Which is what they did with 2.0 and plan to do with 3.0 -- at which point they promise stability.

In general you want to stop making incompatible changes when you have finalized a good design and fixed all the major pain points from the early releases that the community brought forward.


I've been writing Swift since day 0 of its announcement - the migration issues aren't that big of a deal even for 10k lines of code, especially if you did it at each step. Sure it isn't fun, but everyone knew it was a early/beta language.

After 3.x, their won't be huge breaking changes thankfully.

Personally, only issue that bugged me was slower compilation time.

About significant investment, this is just how Apple is. They don't stop the train for anyone, it's get on or off. Same goes for SDK you compile against, certain features you must bake in etc.

Objective-C is 33 years old, I don't know for sure but I bet it wasn't that stable at the start!


Currently? Have people really not migrated to 2.0 yet? It wasn't that bad.


Is it really mature enough that they shouldn't be making breaking changes?


If it isn't, they shouldn't be advising people to build on it.


I'm not sure what exactly you mean. These breaking changes have not been surprises. They've clearly state their intention to evolve the language in public since it was first shown.


No.


Applications are rarely released in explicit versions (from the user side, publicity wise, sure there is a version number in the version control process, but what percentage of Gmail users do you think know what version they are using). If Apple has an application that is successful then they will continue to iterate that code base. If Apple truly is of the opinion that Swift is the language of the future, one would expect them to utilize it going forward. In order to utilize it going forward they'd need to rewrite some of the code base when they fix bugs and change functionality or aesthetics. The remaining code base can be left alone so long as they are confident they can get the resource to work with it if needed in the future. So really, what Apple is saying is, it's still easy enough to get someone to work on Objective-C should an issue arise. When that talent pool dwindles, at that point Apple will need to look at the cost/benefit of rewriting large code bases again. That is all assuming Apple has commited to moving to Swift and away from Objective-C, which I doubt is the state of affairs just yet.


Dogfooding


Wouldn't dogfooding mean writing new software using Swift, where appropriate, instead of re-writing existing software?


I think true dogfooding would require a mix of both new applications as well as migrating older applications over.


I'd say this is more that they don't have time to rewrite current apps and they don't want to mix Swift and Objective-c code so new features in those apps are still written in Objective-c. Maybe they also decided to wait for it to stabilise with Swift 2.0. Updating Swift code when the language is updated is a big time suck.


I think it's more to do with company/dev size. The bigger companies take longer to migrate than smaller startups and lone devs. I'm in a small startup and it was trivial for me to change over to Swift as I'm the only iOS dev. Facebooks SDK is still being written in Objective-C so I guess it's simply harder for them to jump over because it's a much bigger project.


Facebook shouldn't be the reference to point when it comes to their SDK.


Facebook hasn't even gotten their SDK working with dynamic frameworks :/


> The choice to use Swift comes with some tradeoffs, and it appears that Apple has decided it’s generally not worth it for their apps or frameworks yet.

Really, that's your take-away?

> However, there could be a very different story building for iOS 10. Since most of iOS is only dropped once per year, we’ll just have to wait and see in June.

AHHH! You almost get it.

Apple needs time to make the change (and they'll most likely never completely change over to all Swift) for most of the apps they decide to change. They want a nice fluid experience for their customers. Product cycles aren't short, iOS/OS X are at once per year, but that doesn't mean that some changes to them aren't planned out for much longer than a year.


One thing that will not be rewritten in Swift any time soon. https://twitter.com/clattner_llvm/status/613906970890801152


LinkedIn built its new iOS app completely in Swift. Only with Swift 2/Xcode 7 it seemed to be feasible, and then still required Mac Pros to compile everything

http://www.slideshare.net/KyleSherman/swift-at-linkedin


I'm porting my app to swift. I started to feel the pain. admittedly I haven't studied the language systematically.

the biggest pain I think is the error messages. some doesn't make sense. I also don't appreciate the ! and ?.

In my opinion, checking whether a variable is null or not is easier than using ? and ! everywhere.


> In my opinion, checking whether a variable is null or not is easier than using ? and ! everywhere.

Which is why you can do exactly that.

    if let checked = blah { /* checked does not need ! or ? */ }


Arguably the newly supported guard syntax is nicer:

guard let foo = optFoo { Swift.print("oops, this optional thing wasn't optional") }

Swift.print("now \(foo) is in scope and non-nil")


I'm curious, if my variable "a" is indeed null, and when I say a!, what will happen?

will it be a runtime error? like a memory access violation in c++?

what's the benefit of adding !? if it generates the same access violation runtime error?


yes, it is a runtime error. given the code

let foo = bar!

If bar is nil, you'll get a runtime error "unexpectedly found nil when unwrapping bar"

in my opinion, the benefit of optionals in general is that it allows you to guarantee at compile time that certain variables (non optionals) will _never_ be nil, which enables all kinds of compiler optimizations.


You still need to use ! inside that block, but you can use it confidently that it won't result in you accidentally unwrapping a null object.


No, you use checked instead of blah. If blah is type 'Blah?', Checked is type 'Blah'.

Edit to add: And unless something has changed since I last tried it, you can also just shadow blah so that inside that scope you're referring to the unwrapped one:

    if let blah = blah { /* use blah here, it's unwrapped */ }
It looks kind of silly, but I have used it where there was no better name for the unwrapped value.


this doesn't look better than c++ syntax.

I still don't understand the point of ! and ?

less is more, swift ought to know.


I don't think it's trying to be syntactically better than C++. It's an improvement in semantics. Once you unwrap an optional with "if let", it cannot cause an access violation.

You seem to be insisting on using ! and then blaming the language for letting you shoot your foot off with it...


Sorry, I don't get it.

the example you gave is like the following c++ code:

XXX *object = null;

if ((object = anotherpointer) != NULL)

{ ... }

The point is, ! is only useful, when it can detect null pointers during compiling time. but it doesn't.

the way ! is used, as suggested by your example, is also doable in C++, it is just a habit thing.

in c++, with good habit, you won't have problem. in Swift with bad habit, you will have the same problem.

then what good is !,


No, you don't seem to be getting what I'm saying. I'm saying don't use !, and showing you how to avoid using it in a common pattern. Using 'if let' instead of ! does give you compile time verification of correctness.

! is there for the small number of cases where that's not possible. And it makes it much more obvious where you've got a potential problem, because the '!' is a literal code smell. You can't really do that with c++.


Ever since the guard statement was introduced I think you should never, ever use the ! as operator. It still has some sense when using as a type, for example for IBOutlets.


There are _very_ few cases in which you should use the ! operator and all of them are tied to Interface Builder and non-finalized Obj-C APIs. Just use the if let construct or guards.


here is a case that I have to use !, maybe I'm using it wrong, please correct me.

so I have this "member" in a class

class XXX: UIView

{

   var member: BBB

   init()

   {

      super.init()

      self.member = BBB(self.frame)

   }
}

if I do this, I got the error that self.member is not initialized before super.init

if I move it to before super.init, self.frame isn't available.

my solution to this chicken-egg thing is putting a ? after "member"


    let member = BBB()

    init()
    {
        super.init()
        member.frame = self.frame
    }
?

Note that since this is a UIView subclass, you're actually implementing init(frame:) and init?(coder:), not init(). I usually unify the two by declaring subviews as lets and initializing them in a private setup method.


While someone replied with a solution to this problem that may work for you, I will say that I do find the rigidity around initializers frustrating.


Interesting look. Although I will point out that not all classes are equal. Lines of code would be a little more meaningful to me, but kudos to the author for researching what was available.


I would say that new apps are being written in Swift, while the old ones will stay with Obj-C. It's too complex to mix Obj-c and Swift, so why go through the trouble?


It's trivial to add Swift to an Objective C project. Create a bridging file then either create a new Swift class or extend an existing Objective C class.

extension MyViewController {

  func myFirstSwiftFunc() -> Bool {
     return true
  }
}


Mixing both adds complexity to the codebase, though. Might as well stick to Objective-C for legacy projects and Swift for new projects.


I think you're overstating the complexity. The real problem is once you see how visually noisy Objective C is compared to Swift, you'll get the urge to translate your ObjC code.

    NSString *s = @"Swift is the future";
    UIViewController *vc = [[UIViewController alloc] init];
    NSArray *names =  @[@"John", @"Paul", @"George", @"Ringo"];
vs

    let s = "Swift is the future"
    let vc = UIViewController()
    let names = ["John", "Paul", "George", "Ringo"]


But the "noise" also reduces ambiguity. For example, you can search the code and see s is a NSString in Objective C. You can't do this in Swift.


Can't say that I see the value in that but you do have the option of adding types the old fashion way.

    let s = "Swift is the future"
    let s:String = "Swift is the future"
It's just a matter of making a coding convention.


You can just alt-click on the variable in Xcode and see the inferred variable type instantly, no matter what the type is or where the variable is declared. No need to search. You can't do this in Objective-C.


Well you can see that s is a string because of the assignment, and if you want you can also add type annotations like

let s: String = "Swift is the future"


Why is it "too complex" ? The article mentions that the one "app" apple does use Swift in is a mix of Objc and swift


(Calculator in the standard iOS distribution and some classes of the WWDC app.)


I think majority of these articles are being written by developers who always assumed that Apple would never move away from Objective C. By introducing Swift Apple has now directly threatened their unique skill set. In my opinion Apple recognized the threat from React Native / Cordova / RoboVM and had long term vision to introduce a new programming language that would allow Python/C++/Java developers to easily develop for iOS.

If you are interested in getting into Swift programming, don't let these article fool you into getting discouraged. This article is simply spreading Fear, Uncertainty and Doubt.


I don't think Apple ever intended to phase out Objective-C in favor of Swift. Swift is just another option for developers, in the same way that C# is an easier option for Windows developers. Objective-C, just like its predecessor C, can be used in a huge array of environments, ranging from servers to clients and everything in between. It would be impractical and close to impossible to support Swift in all these environments. As a result, Apple is much better served by code written in Objective-C, especially in areas such as the operating system and closely related system code.


Totally false: dynamic dispatch in performance critical code like the OS ?


The operating system is not just the kernel. Even since the time of NexT, Objective-C was used to implemente some of the foundational libraries provided by the operating system, in the areas of graphics, window management, and file access, for example.


The title is one of those Betteridge's Law ones ("Any headline that ends in a question mark can be answered by the word no."), where a story that doesn't give the answer the author wants or is inconclusive has a title framed as a question. But in this case, it's one where the answer is "Yes", not "No", because usually a Betteridge's Law title asks if an unlikely proposition is true, rather than if a likely proposition is false.

Of course Apple are using Swift, but they're not going to rewrite everything in it overnight. Heck, they probably aren't ever going to rewrite. Swift will only be used for new stuff.


"Apple has decided it’s generally not worth it for their apps or frameworks yet"..

...to RE-WRITE them in Swift.


The OS and built-in apps have tighter performance requirements than third party apps. I'm guessing Swift needs to catch up to Objective-C in heap and CPU usage before it's considered.


Who module optimisation for generic code. Getting rid of dynamic dispatch when setting classes as final can do a amazing things when it comes to performance. Obj-C would have to dispatch out to C/Obj-c++ for that, now you can use Swift.

Although Objective-C got nullable arguments, it still isn't as safe as Swift. You're always a null pointer away from a crash... or unexpected behaviour as calling shit on nil doesn't matter


May be or not?




Applications are open for YC Summer 2021

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

Search: