An introduction to Swift
This is a modal window.
Das Video konnte nicht geladen werden, da entweder ein Server- oder Netzwerkfehler auftrat oder das Format nicht unterstützt wird.
Formale Metadaten
Titel |
| |
Alternativer Titel |
| |
Serientitel | ||
Anzahl der Teile | 163 | |
Autor | ||
Lizenz | CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 3.0 Unported: Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben | |
Identifikatoren | 10.5446/50485 (DOI) | |
Herausgeber | ||
Erscheinungsjahr | ||
Sprache |
Inhaltliche Metadaten
Fachgebiet | ||
Genre | ||
Abstract |
|
NDC Oslo 2015135 / 163
6
13
16
17
18
19
20
21
22
25
28
29
30
31
40
41
44
45
49
51
52
53
54
55
57
58
60
61
71
74
75
76
78
84
85
91
92
93
94
95
96
98
99
100
105
106
107
112
115
116
117
118
122
123
124
125
127
128
129
130
131
132
133
135
136
142
144
150
151
153
155
156
157
159
160
00:00
QuellcodeAppletProgrammierungIndexberechnungProgrammierspracheBitrateTypentheorieWasserdampftafelApp <Programm>Physikalisches Systemsinc-FunktionRichtungKlasse <Mathematik>ServerMultiplikationsoperatorObjektorientierte ProgrammierspracheRückkopplungSpiegelung <Mathematik>AusnahmebehandlungInformationsspeicherungZeichenketteKonstruktor <Informatik>Lokales MinimumBeweistheorieSoftwareentwicklerMaskierung <Informatik>Twitter <Softwareplattform>CodeAuswahlverfahrenQuellcodeAutomatische HandlungsplanungMaschinenschreibenPufferüberlaufKeller <Informatik>PunktAutomatische IndexierungMAPRechter WinkelStatistikKartesische KoordinatenGefangenendilemmaFunktionale ProgrammierspracheVariableProgrammierungElement <Gruppentheorie>GraphSelbst organisierendes SystemMinkowski-MetrikZahlenbereichInformationResultanteSichtenkonzeptQuick-SortLaufzeitfehlerEin-AusgabeGanze ZahlGüte der AnpassungArray <Informatik>Repository <Informatik>SondierungComputeranimation
05:58
ZeichenketteHochdruckSystemzusammenbruchJust-in-Time-CompilerModemGenerizitätVerweildauerAuflösungsvermögenSchreib-Lese-KopfDämpfungInnerer PunktSystemzusammenbruchElektronische PublikationZeichenketteProjektive EbeneKlasse <Mathematik>Funktionale ProgrammierspracheSystemaufrufCodeMatchingGeradeEinfügungsdämpfungApp <Programm>ProgrammierspracheAlgebraisches ModellMusterspracheMultiplikationsoperatorWurzel <Mathematik>TypentheorieHochdruckKartesische KoordinatenArray <Informatik>LaufzeitfehlerProgrammbibliothekBimodulMereologieMaschinenspracheAuflösungsvermögenGebäude <Mathematik>Ein-AusgabeIdentifizierbarkeitResultantePunktSoftwareentwicklerGenerizitätProgrammierungMailing-ListePhysikalisches SystemGrundraumARM <Computerarchitektur>Formale GrammatikEndliche ModelltheorieInterpretiererKategorie <Mathematik>Virtuelle MaschineMomentenproblemRechter WinkelGrenzschichtablösungAggregatzustandNummernsystemMAPPRINCE2Lokales Minimumsinc-Funktion
11:55
FehlermeldungServerZeichenketteENUMBenutzerfreundlichkeitSichtenkonzeptZellularer AutomatObjektorientierte ProgrammierspracheTaskGruppenkeimSchnittmengeMaßerweiterungAnfangswertproblemEin-AusgabeHyperbelverfahrenVariableTaskExistenzaussageNichtlinearer OperatorCompilerArithmetisches MittelFunktionale ProgrammierspracheInterrupt <Informatik>DefaultBitGeradeTypinferenzSpannweite <Stochastik>Kartesische KoordinatenMulti-Tier-ArchitekturCodeKondition <Mathematik>CASE <Informatik>Projektive EbeneBefehl <Informatik>InformationZeiger <Informatik>SichtenkonzeptMultiplikationsoperatorRechenschieberKlasse <Mathematik>SoftwaretestKonfiguration <Informatik>Message-PassingGenerizitätZahlenbereichMaschinenschreibenAusnahmebehandlungLoopGanze ZahlTwitter <Softwareplattform>PerspektiveExpandierender GraphOpen SourceFehlermeldungExogene VariableParametersystemApp <Programm>AbzählenInformationsspeicherungAbstimmung <Frequenz>ResultanteGlobale OptimierungGebundener ZustandTabelleVisualisierungKeller <Informatik>E-MailSummierbarkeitPufferüberlaufMaßerweiterungSelbstrepräsentationInnerer PunktSkalarproduktMusterspracheSystemaufrufTypentheorieMustervergleichObjektorientierte ProgrammierspracheIdentifizierbarkeitOverloading <Informatik>ProgrammierspracheGamecontrollerKette <Mathematik>sinc-FunktionMAPBoolesche AlgebraKategorie <Mathematik>ENUMFramework <Informatik>Aussage <Mathematik>Fibonacci-FolgeGewicht <Ausgleichsrechnung>ZeichenketteSkeleton <Programmierung>InformatikArithmetischer AusdruckAutomatische HandlungsplanungSoftware Development KitShape <Informatik>ProgrammbibliothekMereologieSchnelltasteElektronische PublikationPrimitive <Informatik>URLStichprobenumfangKonstanteGruppenoperationTouchscreenPhysikalisches SystemStrömungsrichtungVollständigkeitKonstruktor <Informatik>Zellularer AutomatTranslation <Mathematik>Mapping <Computergraphik>VarianzDeklarative ProgrammierspracheRichtungSoftwareentwicklerGebäude <Mathematik>OpenURLBildgebendes VerfahrenOffene MengeVersionsverwaltungDeskriptive StatistikKomplex <Algebra>GraphfärbungSortierverfahrenFolge <Mathematik>BenchmarkÄhnlichkeitsgeometrieNetzbetriebssystemNP-hartes ProblemArithmetische FolgeGraphMathematikEinfache GenauigkeitValiditätZweiDifferenteQuick-SortWellenpaketDatenflussHochdruckTemplateInformationsüberlastungSkriptspracheEreignishorizontVererbungshierarchieDemo <Programm>BetafunktionDatenstrukturEndliche ModelltheorieFundamentalsatz der AlgebraInterface <Schaltung>GleitkommarechnungPunktAbgeschlossene MengeProtokoll <Datenverarbeitungssystem>ServerAlgebraisch abgeschlossener KörperPoisson-KlammerProgrammierungTermTupelProdukt <Mathematik>EindeutigkeitGrenzschichtablösungFreier ParameterRechter WinkelDatensichtgerätMomentenproblemAggregatzustandLie-GruppeMultiplikationWeb SiteNeuroinformatikNegative ZahlRechenbuchWort <Informatik>Data DictionaryBeamerVorzeichen <Mathematik>EinhüllendeLesen <Datenverarbeitung>ComputersimulationGüte der AnpassungWarteschlangeLaufzeitfehlerWorkstation <Musikinstrument>MaschinenspracheSystemprogrammierungPhysikalische TheorieMatchingWhiteboardSeidelProgrammschleifeeCosTypsichere SpracheExistenzsatzt-TestBildschirmfensterSystemplattformRahmenproblemMinimumARM <Computerarchitektur>RoutingSpeicherbereichsnetzwerkNatürliche ZahlDickeService providerCOMDienst <Informatik>AppletXMLComputeranimation
Transkript: Englisch(automatisch erzeugt)
00:02
All right. Hello, everyone. Thank you for coming. And I hope you're enjoying NDC so far. I've got to say, I've been to a lot of conferences, but never did I have a stage suspended between heaven and earth. You've just got to look.
00:22
It's not quite stable, this whole construction. Just look at my water bottle. And I hope I don't fall. Anyway, so the other thing, on behalf of all speakers in this particular slot after lunch, I have just one piece of feedback for NDC organizers.
00:40
The food is way too good, and there's way too much of it. And so I hope you'll be able to stay awake for this talk on Swift. If you have any questions throughout, then please do raise your hand or shout out. And I'll try to make this interactive. And then at the end, we're probably going to have some time for questions. I do have another talk back to back 20 minutes later.
01:02
So if you don't catch me immediately after this one, please feel free to stay in touch on Twitter. Otherwise, just meet me, and I'll be happy to talk. So how many of you, just to get a general feeling, how many of you are iOS developers? OK, so not a whole lot, but there are some. And how many of you are using Objective-C today?
01:23
Maybe building Mac apps, iOS Mac, well, everything. OK. So basically, I wrote down in the abstract that there is no prerequisite here to know iOS or Objective-C. This is just an introduction talk to Swift. And it's actually been pretty successful, this idea of mine, to do a general introduction talk to Swift,
01:41
because Apple has just announced a few weeks ago that they're planning to make Swift a programming language for things other than just iOS and OS X. Generally, it's a pretty good systems programming language, which can be pretty successful in spaces where people are using Rust and Go and C++, of course, and Objective-C.
02:03
So here's a graph. Here's a picture. And that's some pretty biased statistics based. It's language popularity based on Stack Overflow searches and GitHub repos and a bunch of other informal sources like that.
02:20
And so what would you say happened to Objective-C popularity around 2009, the end of 2008? What happened? What? The iPhone, and more specifically, the release of the App Store. If we just had an iPhone, but we couldn't build apps for the iPhone, I don't think Objective-C would have been
02:42
that popular outside of Apple. But in late 2008, Apple announced the Apple Store. App Store and people were able to submit applications to run on iPhones. And it's been pretty popular since. And then what happened to Objective-C popularity somewhere around this peak in 2014?
03:02
Swift happened. And again, this is an informal survey of developers. But it does look like iOS developers and Mac developers are slowly moving to Swift. Actually, not so slowly. It's just been a year since Swift has been released. And it's gaining really nice popularity.
03:21
It's still not one of the top 10 programming languages, but it is extremely popular. And I'd like to show you why in this talk. So basically what we're going to do, I'm going to give you a couple of reasons why Objective-C is a horrible, horrible language. And then I'll give you a few reasons why Swift is an elegant, beautiful, incredibly concise language
03:41
to use. And then I'll build a little app with you, just completing pieces of code here and there to show you what Swift is capable of. And then we'll have some time for reflection questions, future directions, stuff like that. By the way, I'm not affiliated with Apple in any way. So all the stuff I'm going to say is just based on public information.
04:01
So here's exhibit A of how Objective-C is a horrible, horrible programming language. For the Objective-C developers in the audience, this is going to look familiar. But otherwise, I just want to point out this is a simple method that takes an array and a string. And it tries to see if that array contains that string.
04:21
And it's supposed to return the index of the object of that string in the array. And it turns out if you pass in a string which is null, then you get back a value called ns not found, which is basically the maximum unsigned integer value. And that says no, there is no null in that array because arrays cannot contain nulls.
04:41
That's the way the Objective-C runtime works. But if you pass in a null array, then the Objective-C behavior is that you get zero as the result of this function. And there are some good reasons for this, but for me, it's just another proof that Objective-C is a horrible, horrible programming language. Here's another example, exhibit B.
05:02
So here, you can see on the left-hand side, the variable type is NSMutableArray. On the right-hand side, the type is NSArray. And actually, NSMutableArray is a subclass of NSArray. But this code still compiles. There is a sort of a downcast there.
05:20
And the interesting thing, the cast succeeds at runtime. It is only after the cast that when you try to use an NSArray as if it were mutable, so for example, if you try to add an object to an array which isn't mutable, then you get an exception at runtime. What are you talking about? Of course, there is no selector called addObject
05:41
on the NSArray class. What are you talking about? Exhibit C, for those of you who are still unconvinced, here we have an NSMutableArray. This is a mutable array, that's all right. And then it doesn't really quite have a type for the elements. So I can add a string, I can add a number.
06:03
Okay, fine, that's fine. Many languages are dynamic with types, you know, kind of loose with types. But then you can take out that int and put it in a variable of type NSString, and that compiles just fine as well, and that line runs as well. And you can even take that string,
06:20
which isn't a string, and print it out, and it prints 17, that works all right. It's only when you try to treat it as a string by, for example, calling a method which only strings have, then you get a crash at runtime. I bow my head in shame at this point. I've been writing some Objective-C for a while,
06:41
for several years, and this is not the kind of stuff that makes you proud as an Objective-C developer, I think. Right, Objective-C guys and girls, right? Okay, so enter Swift, and Swift has been announced in just June 2014, and one of the, I mean, they could pretty much announce anything, I think.
07:02
They could say, this is based on Haskell, this is based on Lisp, this is based on Fortran, and still people would be pretty excited because it isn't Objective-C, you know? And that's pretty much enough for us Objective-C developers. Give us anything that's better than Objective-C, and we're gonna be happy with the result.
07:22
But I contend that Swift is much better than Objective-C, and it's actually a pretty decent language to learn, even as a first programming language. It's modern, it's elegant, so there's some pieces of syntax borrowed from here and from there, which make it a really nice little language, elegant in a language-formal kind of way.
07:42
It's type-safe, so there's much less opportunity for all those ugly downcasts succeeding and then failing at runtime. It's a generic language, so there's built-in support for generic types, collections, stuff like that, arrays. It's a functional programming language with very strong roots in functional programming languages
08:01
like, well, you know, Haskell, Scheme, Lisp, whatever. So there's support for pattern matching, algebraic data types, a bunch of other nice function language features. Another pretty important property, which is shared with Objective-C, is that Swift compiles to native code. So there is no virtual machine, there is no byte code,
08:22
there is no interpretation, there is no VM at runtime that does stuff with your code. It's compiled down to machine instructions. So you take Swift code, you compile it down to ARM, ARM64, and potentially in the very near future to x86 and other operating systems as well.
08:43
It already supports x86 on the Mac, and it will support Linux as well in the future. So it is a native programming language that can give you the performance of a native compiled language like C, C++, Objective-C, and so forth. But at the same time, it can't lose support for Objective-C, and so you can take Swift code
09:02
and call Objective-C methods, and you can write a Swift class and call it from Objective-C. And you can do it from the same project. So you have a Swift file and an M file, Objective-C code, and they can call each other in the same project. And finally, that last point means all the iOS APIs,
09:24
all the Mac APIs are accessible from Swift. And even if there is some low-level C-style API that you really have to call, and you can't directly call it from Swift, you can wrap it with an Objective-C layer, and then call
09:40
that Objective-C code from Swift. So essentially, you can build iOS applications from scratch with Swift. You can mix and match, oh man, you can mix and match Objective-C code and Swift code. You can take an existing library from GitHub and just use it in your Swift project. You can add Swift classes to your Objective-C project.
10:02
It all works, it all works by design. So here are a couple of ways to get started with Swift, and if any of you have your Macs along, you can just sort of try and experiment a little as well. The first way I'm gonna show you is the Swift REPL.
10:23
So this is a little command line app called Swift. You run it and you start typing in Swift code, so two plus two, you know, or hello world, great. And then, of course, you can define classes and functions, so for example, I can define a function called add,
10:41
which takes an int, x and int y, and returns an int, and here's the function, and then I can call the function, and it returns a value, so you know, a REPL for experimenting with Swift features. Now here's the cool thing, again, Swift can talk to all the iOS and OSX APIs,
11:01
for example, Foundation APIs, so suppose I wanna use the NSDate class. Ooh, unresolved identifier NSDate. Well, NSDate is part of a module called Foundation, so in the REPL, I can import Foundation,
11:20
and then here's an NSDate, and sure enough, we can use a type which is definitely not a Swift class, it's a type from the Foundation module, but we can use it just fine, and interact with it, of course, so let x equal NSDate, x date by adding time interval 1.0,
11:44
and so I've just added a second to that date, and so on and so forth. So this is one way, you know, to get your feet wet with Swift. The other is called Playgrounds, and this is a really nice Xcode feature, since Xcode 6, where you can basically,
12:01
you know, play around, you know, on a Playground with some Swift code of your own. So there's a couple of examples here for visualizations and added value that Playgrounds give you, which the REPL doesn't. So the first couple of lines here, for example, this is a loop which, you know,
12:21
takes some initial value, and then starts to apply some operations to it. I can visualize the execution of that loop by just clicking on this little thingy over here, and expand it, and I can see the progression of values in the loop, I can see the final value, or I can see the succession of all the values as either a graph or a list.
12:42
Another example is with colors, and there's similar support for images as well, so if you have a color object, an image object, an animation, you can see what they look like in your app. And finally, you can do interactive programming as well, so the code there on the bottom, it creates a button, it gives the button a background color,
13:02
it gives the button a frame, it gives the button an opacity, it sets the button's title, and it sets the button's text color, and then it calls a method for Playgrounds only called XCP show view, and then here's the button. And you can make this interactive actually, you can subscribe to events that this button would raise.
13:23
Now this is really, really nice for experimentation when learning a new API, this is also a great way to create interactive tutorials. So you can give your students, you can give your fellow developers a nice little playground with a bunch of already built features, and you can tell them, okay, so here you should just write a line of code
13:42
to make this example work a little different. So I really like Playgrounds for training and for experimenting with new libraries. So that's just to give you a general idea of what Swift looks like and what ways you have of experimenting with it. Now the fundamental language principles, and obviously we're not gonna have time
14:01
to discuss them all, are the following. Swift makes a really, really strong emphasis on immutability. And so you have variables which can vary, and you have constants which cannot, which are set and immutable. And there are different keywords for those. You use var for variables,
14:20
and you use let for constants, which you cannot modify. So again, if you're familiar with Objective-C, there's no more NSArray and NSMutableArray, NSDictionary and NSMutableDictionary, NSString and NSMutableString. If you have a string, it could be either in a variable or it could be in a constant. The type is the same type,
14:41
it's just the variable that matters, the type of the variable. The other important proposition is optional types, and I'll come back to that a bit later. It has to do with nullability, and so Swift does away with nullability. Stuff cannot be null unless you explicitly say this variable here may be null.
15:02
And this is such a strong proposition, especially compared to Objective-C where everything pretty much can be null, and when something's null, it doesn't mean you can't call methods on it and get nonsensical values back. The other thing is first-class handling for functions,
15:20
for functional programming concepts like pattern matching. I'll show you a couple of examples. And then of course, again, the full interrupt with Objective-C. Anything pretty much you can do in Objective-C, you can also do in Swift. So I have a couple of examples here. I'm not gonna go into depth. It's just designed to show you in general how Swift is really a breath of fresh air
15:42
in this whole ecosystem. So on top, I have a class, an Objective-C header file, actually. Well, the class is called OComplex, and it has a couple of properties. It has an initializer, which is like a constructor. It has some methods as well.
16:03
And then on the bottom, you have the Swift version of this, a struct complex with properties and with functions and with operators. And operators, actually, overloading of operators, there's a really, really strong proposition in Swift. It makes working with strings,
16:21
it makes working with integral and floating point types that much easier, and you can overload operators for your own classes as well. And so even if I didn't put this white line over here, you'd be able to tell which is old and which is new, right? So there is this sense of elegance coming out of the Swift code, at least for me.
16:42
Here's another little example. It's not so much about length, you know? There's almost the same number of lines. It's about the elegance. And so again, just look at all the parents which are gone. Look at the rectangular braces here,
17:01
which are so typical of Objective-C code, really borrowed from Smalltalk syntax. These are gone. Lots of things are automatic and just sort of flow from the screen. And finally, here's the overloaded operator. So z equals z times z plus c, as opposed to z mult by z add to c,
17:23
which is what happens when you don't have overloaded operators. So again, even if I didn't put this line here, you'd be able to tell which is old, which is Objective-C, and which is Swift. So again, I'm not trying to teach the language here, but I do want to show you a couple of representative examples
17:40
before I just write a couple of classes and the little iOS application. So here's exhibit D, which shows you, well, the foundation of Swift's pattern matching around the switch statement. So the scenario here is that we have the fair class for someone's plane ticket, you know,
18:01
and I want to calculate the mileage bonus they're going to get from that particular flight. So the switch statement can go over strings, and that's already something Objective-C cannot do, and many other languages can't do either. But then a case statement can include multiple cases. Okay, so F, A, J, and C are all business
18:22
or first class tickets. And then Y and B are full fare economy, and M and H are discount, but it's a high tier discount. And then I can even do complex conditional operations. So I can assign that fare class to a temporary variable here, and then ask questions of it.
18:42
So if it has the R prefix, the whole string, then it's an upgrade ticket, and it doesn't deserve any bonus. So that's a very basic example of Swift's switch syntax. And here's an even more powerful example, which shows you a sum type, an enum, an enum called HTTP response.
19:02
And enums in Swift, they have state. It's not just a couple of integers that vary. So for example here, I have a success case for HTTP response, which has a body of that HTTP response. And I have an error case, which has a description and a status code for that error.
19:21
And then I can pattern match on those in really, really clever, elegant ways. So assuming HTTP get request returns one of those enums, it can go two ways. It can go error or success. But even if it was an error, I can do stuff like error description and status where the status was greater than or equal 500.
19:43
And that's an internal server error, as opposed to all the other cases, and as opposed to the success case. And in all these cases, you can see that there's pattern matching syntax that deconstructs the enum and puts it in nice little variables that you can use again.
20:01
And there's very similar support for tuples as well. And so in functional programming languages, this would typically be called a sum type, and a tuple is essentially a product type. And in both cases, you have this really nice language level support for deconstructing these algebraic types into their constituent variables.
20:22
And this is really, really handy once you get used to it. And so here's, this is probably one of the examples most influenced by functional programming. Here's another nice feature of Swift. It's designed for extensibility. So it's really easy to take existing types and add features, add operations, extend them essentially.
20:41
And so here's an extension of int. You know, it's not a very practical extension, but it's one that you can actually write. And so here I'm extending the int type to have a method called repeat. And the repeat method takes a function. This thing over here, task, is a function.
21:00
And it's a function from ints to void, from int to nothing. And then what that repeat function does is just call that task as many times as the integer I'm holding in my hand. So you can do stuff like three dot repeat and pass in a function which will be invoked for, which will be invoked three times
21:22
with the values one, two, and three. And so there's a bunch of syntax on this slide which again shows the conciseness of Swift. First, you can see the range, the range syntax for loops, right? So you can do x in zero to self. And you can see this conciseness here around the closure, the function that's being passed
21:43
to the repeat function. There is no argument. That function takes an argument but it isn't there. You can just use dollar zero for the first argument and dollar one for the second argument and so on. There is this conciseness in the syntax where you need it or you can spell it out
22:01
if you really need this to be explicit. And here's a final exhibit, again, designed to convince you of the value of Swift. This is a little playground I used to solve a problem for Project Euler. Is anyone familiar with Project Euler? It's basically, yeah, okay, it's basically a website with like a hundred,
22:23
no, maybe more, several hundred problems ranging from the very simple, like printing numbers which are multiples of five, to really, really hard math problems. And so the second one is really easy. It's basically enumerate all the terms of the Fibonacci sequence which are smaller than four million,
22:41
look for the even ones, divisible by two, and sum them all up. And so this is a classic thing to do with a playground. As you experiment with the code, you can really see the execution of it. You can see the progression of the Xs which are part of the sequence itself. You can see the progression of the sum variable which sums up the even terms.
23:02
It's really, playgrounds are really designed for this sort of experimentation. So let me, let me just, before I write a little app with you, let me just focus on the one thing that maybe makes Swift unique in the mainstream programming languages, you know, C sharp, C++, Java, Python, all that lot.
23:23
This is a quote from Sir Charles Anthony Richard Hoare from 2009 when he was accepting some award or other 50 years of really extraordinary computer science work. And he said, I call it my billion dollar mistake. It was the invention of the null reference.
23:40
And there's a bunch of other texts here where he explains why he thinks it's such a horrible mistake and why it's a billion dollar one. But Swift doesn't have nulls by default. And so here's a tiny little example which shows how this nullness and non-nullability still works with APIs that produce nulls occasionally.
24:04
So for the Objective-C developers, here's a method which you might be familiar with, table view dequeue reusable cell with identifier. This is a method used in UI applications on iOS, which gives you some object or other that you're supposed to use a UI table view cell.
24:23
Now this method is part of the UI kit framework, and it's not a Swift method. So what it returns is not even a proper class. It's not a table view cell. It returns something like object, an arbitrary thing which can be anything.
24:42
In Swift, the way to express an arbitrary object is using the any object type. But there's a bonus. That thing you're getting back could be null as well. Not only do you not know the type, it can also be null altogether. And the way to express that in Swift is by adding a question mark.
25:00
So this is an any object question mark, a nullable any object. It can be any type, and it could be null as well. But then you wanna test if that arbitrary, weird thing you got back is actually of a specific type and is actually not null. So you have this really nice as operator
25:21
and some nice syntax around if statements. So this line over here says, well, see if that cell variable is actually of type UI table view cell, and if it's not actually null. If those two statements are true, then put the result of type UI table view cell
25:42
back in a temporary variable called cell. And then if I get into that if statement, I know for sure that cell is of type UI table view cell and it isn't null. And again, the language guarantees that if you don't have a variable designed to contain nulls, it will not contain nulls.
26:01
So you have to be explicit about nullability and in most cases, you don't want nullability in the first place. And then inside that little if statement, there's another example which is now popular in some other languages as well, optional chaining. Ooh, optional chaining on nullable things.
26:20
So what you can do, what you can see here is that the text label and detail text label properties of the cell are actually nullable objects. So these properties might be null. And so to avoid having to test and then use them, there is this chaining operator question mark dot.
26:40
And you have that for member access expressions, for array access expressions, for method calls. So you can say conditionally, if that property isn't null, then I want to access it. If it is null, just do nothing. And that's a really handy way of working with existing code which already has nullable stuff built in.
27:01
So that's another principle of Swift that you're going to see in your code. So let me show you a quick example of building a little iOS application with Swift. I already have the skeleton for the app itself. I didn't want to waste time creating a new project and putting UI controls on board. I just want to write a few classes,
27:21
just show you a bit of Swift syntax. So the app itself is going to be extremely original. It's going to be a to-do app with to-dos, tasks in this case. And the first thing we're going to need is a class task. And that class is going to need a text property with the title for that to-do item
27:41
and a due date. So I'm going to make the text property a string. And it's going to be immutable, a read-only property. On the other hand, the due date is something a user can change. So I'm going to make it a var. And that's a read-write property.
28:01
Next, we're going to need an initializer, which assigns those values. Particularly, I already have an error because my class doesn't have an initializer. And that tiny, teeny thing over here says the stored property text without initial value prevents synthesized initializers. In other words, you have a read-only property.
28:23
And you're not assigning to it in any of your initializers. So that's invalid. OK, so we need an initializer. And that initializer is going to take text, which is a string, and due date, which is an NSDate, and assign them.
28:42
So self-due date is equal to due date. And I might also make an initializer a convenience initializer, which takes only the text and calls the other initializer. So the text is going to be text.
29:00
And the due date is going to be a new NSDate. Right. What does it want from me? Expected separator. What? OK, come back to that. Next, we need isOverdue, a Boolean property which says if the task is overdue.
29:23
And that's going to be a computed property, which is why I have it here even. So isOverdue is a Boolean property. And what I'm going to do here is just check if the due date is before or after the current date. So NSDate is the current date.
29:40
And I'm going to do, what's the method called? I forget. Does anyone remember? There's a method that checks if, OK, time interval since date is one way of doing it. So time interval since date, due date returns, well, the time interval since that date.
30:02
So if NSDate time interval since date is positive, then we are not overdue. So actually less than 0. Right? Am I right in my calculations? We are overdue if the interval since the due date
30:22
is negative. I think so. In any case, finally, we have a snooze method, which is supposed to snooze that task for a while. So here's snooze. And in snooze, I'm going to say due date equals due
30:42
date, date by adding time interval. And I already have a handy constant for it, seconds in day, task dot seconds in day. So whenever the snooze method is called, we just snooze that task for 24 hours. OK, next up is a nice little extension.
31:03
So, so far, I just had the task class, which is like my model class. But then I have an extension of it, which I intend to use for the UI only. So this is my way of separating these concerns. I have the model class, which is pretty clean. And I have an extension for display purposes. So here, I want a due date string computed property.
31:23
Due date string of type string. And what I'm going to do over here is test. So if I'm overdue, I'm going to return past due. This is, again, for display purposes only. And then I'm going to switch on the due date.
31:42
Actually, I'm going to switch on the due date, due date, time interval since date, NSDate. And so I want to see how much time exactly I have until that moment arrives. And actually, the other way around, NSDate,
32:04
time interval since date, due date. Okay, so K is zero to anything less than an hour, I'm going to say very soon, okay? And K is an hour to a day, I'm going to say soon.
32:26
And in all other cases, I'm just going to return a date. So I'm going to use a date formatter. And this, again, goes to illustrate that you can just use whatever APIs are available to you. It's just another language. It doesn't mean the framework you have to use changes
32:42
in any way. So I have a time style, none, and a date style, medium. This is another interesting example. This is actually an enum. And so officially, the type of that date style, the type of that time style and that date style
33:03
is NSDate formatter style. And so it's not actually called none, it's called no style. But the type inference is powerful enough to know that if it's an NSDate formatter style, then I can just say .nostyle. And similarly, the date style will be medium style.
33:25
And then I'm just going to return formatter, string from date, due date, and just display the due date in my UI. Okay, so we have this extension built in. Last piece of code I want to write,
33:41
which is really strongly integrated with the UI, is in my view controller over here. And so what I have over here is a placeholder for a welcome message. And again, this is just to show you that you can really, really easily use Objective-C APIs, stuff from the framework in your Swift code.
34:00
So here, I'm going to use an UI alert controller for displaying a welcome message. UI alert controller with a title, welcome, a message, welcome to the tasks, to the NDC tasks app, and preferred style alert.
34:22
And again, I'm going to remove the enum name from here. And then eventually, I'm going to present that view controller using present view controller, alert, animated true, completion nil. And I'm going to add a couple of buttons
34:40
to that little alert view controller. So I'm going to do add action, UI alert action. These are just buttons. And so UI alert action has a title, which is going to be, let's say, dismiss style, UI alert action style default.
35:01
And the handler is going to be nil for this one. And I'm going to add another action, another UI alert action. And this one is going to be more info, UI alert action style default as well. But this one is going to have a handler. And this is just to show that you have closures
35:22
in Swift as well. So this thing over here is a method that gets invoked when that action is clicked, when the user clicks more info. And what I'm going to do here is UI application, shared application, open URL,
35:41
NSURL with the string ndcosla.com. Okay, and I'm probably missing a couple of braces somewhere. Let's see. No, that's not right.
36:02
Okay, so this is one, and this is two, and then I'm closing this one, and I'm closing that one. And the action's done. Well, I guess let's just build. What? What's that?
36:23
Open bracket, open bracket. This one? No. This one fills the UI alert action. This closes the UI alert action.
36:43
Oh, no, no, no. The initializer returns no. The error makes no sense. Let me just, this is exactly why I already have the whole thing filled in.
37:01
So here's the view. Oh, I did unwrap it. Well, yeah, actually it does make sense because it might fail if the URL is malformed. Good catch. Okay, yeah, okay, anyway, the rest of it is pretty much the same. So let's run this little application.
37:24
It's a really rudimentary table view, basically. So this is the simulator, and buy flowers and run this demo are due soon, and let me create a new task here, move on, add, we have that as well,
37:42
and I can snooze them somehow. Maybe I forgot to add the code to actually snooze them, but I can delete them. That works. Anyway, very well. We have this little iOS application that's using Swift from all directions,
38:03
and next thing I want to talk about, which I want to actually show you a demo of, but I do want to just give you a brief look of what it feels like, is adding Objective-C code to a Swift application. So let me just walk you through the experience in Xcode itself. So say I want to create a new file
38:22
in that project, and the file I want is an Objective-C class. There is a template for this, actually, somewhere or other. Let's create an Objective-C file. I'm going to call it just, you know,
38:41
objclass.m. Next, I'm going to tell Xcode where to put it, and then here's what I wanted to show you here, essentially. You get prompted to create an Objective-C bridging header. Xcode says, by adding an Objective-C file
39:01
to this previously Swift-only project, you will create a mixed target, and would you like Xcode to make it possible for both languages to talk to each other inside the same project? So obviously, if you have, say, a framework, and you want to access it from your application, they don't have to be in the same language, but within the same project, this is pretty impressive,
39:23
and it's not something you often see when interrupting between languages. And so if I do hit yes, what basically happens is that Xcode creates for me this file over here, called ndctasksbridgingheader.h, and here I import, I include,
39:43
any header files which contain declarations I want accessible to Swift. So this direction is explicit. I have to tell my compiler which Objective-C classes I want to make visible to Swift, but that's the only thing I have to do, so I just put import statements in here
40:01
for my Objective-C classes, and they are available to Swift. There is an automatic mapping layer which maps everything. In the other direction, it's even easier. If you write a Swift class, it is automatically, by default, visible to your Objective-C code, so it's really seamless to make this bidirectional interrupt
40:21
between Objective-C and Swift in the same project. And again, I wish we had a little more time to expand on this, but I'll just leave it at that for now. So just going back to the slides, there is a couple of final points I want to make before I leave some time for questions as well. First of all, the whole interrupt story which I was just hinting at
40:40
and showing you in Xcode, there's two directions, essentially, like I said. Swift code can access Objective-C code through those generated header files, the bridging headers, and Objective-C code can access Swift classes automatically, just by magic that the compiler provides.
41:00
Last thing I want to talk about is the Swift 2.0 beta. And this was announced just, you know, at WWDC 2015, which was a few weeks ago, and Apple is taking Swift to a slightly different level than previously. There's been a few minor releases since last June, since June 2014,
41:21
but this is going to be a major one, which is probably due, you know, this fall or so, maybe along with the new iOS and new OS X release. And the major announcement about Swift 2.0 is that it's going to be open source. The compiler itself and the libraries, the Swift runtime,
41:41
the Swift libraries, are going to be open source with a permissive license that you can actually contribute to and reuse. And there will be a Linux port for Swift. And because the Swift compiler is based on LLVM, it's probably going to be fairly easy to port it to other platforms as well. So if you want to use Swift on Windows,
42:00
for example, that's definitely going to be possible at some point. Now, by making this step, not the open sourcing step, the porting to Linux step, Apple is saying that Swift isn't just a language for building iOS applications and OS X applications. From Apple's perspective, Swift is a systems programming language. You can use it to build anything.
42:22
You can use it to build operating systems for all daycare. And again, it started as a totally proprietary thing that Apple built, as they always do, you know, in a cavern somewhere, floor minus 33 in California. But it ends up as an open source project
42:43
that we'll actually be able to use freely and possibly port to other platforms, creating cross-platform apps that compile down to native code. No performance hit, no runtime, no translation layer. There are also some pretty considerable language features in Swift 2.0.
43:01
Notably, there's error handling support, exception handling, essentially, with a few statements designed for exception handling. There's something called defer, which means you can... It's kind of like C++ destructors. You can declare a piece of code to run at the end of the scope, and this helps with...
43:20
It's kind of like try-finally in other languages. There's a feature called protocol extensions, which means, basically, you can take a class that conforms to an interface and extend the interface, so basically adding extensions to all classes that support a particular interface. And Apple is also working,
43:40
and this is really a crazy proposition, Apple is working on changing Objective-C so that it is more friendly to Swift code. So Apple is adding to Objective-C, for example, generics support. To Objective-C, which didn't have generics since 1983, when it was first announced.
44:02
And this is only for making Swift code more readable, comfortable, when working with Objective-C APIs, so that, again, instead of any object, you'd get specific types. Similarly, Apple is adding nullability annotations to Objective-C, so that methods can specify
44:23
if they return a nullable or non-nullable entity. Again, just to make these things more consumable from Swift. So I think Apple is indirectly making it pretty clear that it considers Swift the future of mobile app development for iOS,
44:41
of app development for OS X, and also probably of app development in general, from Apple's perspective anyway. And of course, needless to say, there's been many, many apps submitted to the App Store using Swift in the past year, and I expect these numbers to grow. So this is great.
45:00
We have about 13 minutes for questions. I'll be very happy to take them. Another thing I was asked to remind you of is that you should vote when going out. The voting thing is over there. Just vote. It's extremely important for me and for the conference as well to know how this went. If you have any extra questions later,
45:20
which you don't get a chance to ask right now, then please be in touch on Twitter or try to catch me later after my second talk today. So we're going to have some time for questions. I think I have mics somewhere over here, or I can just repeat questions if you'd like. And in any case, I really appreciate you coming, and I hope you enjoy the rest of NBC.
45:40
So thank you very, very much. So yeah, thank you. Questions, please. Yes.
46:11
Okay, yes, so you're not asking a question. You're basically adding a vital piece of information. In the next version of OS X, Apple is making Swift available as part of the operating system
46:21
so you can start writing scripts, for example, such as build scripts in Swift. And indeed Swift, because it doesn't really require any structure from your application, is really suitable for scripting tasks as well. For example, print hello world is a valid Swift application. You don't need main methods or classes
46:41
or all that fluff around, and it's really pretty suitable for scripts. That's a great comment, yep. Yes. Okay, so the question is if there's support
47:00
for two-way data binding, like you're probably coming from Angular or WPF or XAML. Well, this is not a Swift question. It's actually a Cocoa and Cocoa Touch question, which are the frameworks used for UI development. Currently there is no two-way binding support built in. There are some frameworks that are trying
47:22
to make this a little easier, but built in you do not have bidirectional binding support for primitive variables. You know, all the sample code you see in any case would bind to a UI object, like a label, and then ask that label what the text is, so you know,
47:41
the way we used to do it in the 1990s. That's not a Swift thing though, unfortunately. Okay, I bet if we wait long enough someone will have a question eventually. It always works this way, yes, yes,
48:01
but you'll have to raise your voice, like really raise it. I can't hear you, I'm sorry. Are there problems with switching? Ah, obvious performance gains. Well, theoretically speaking, yes,
48:21
because Swift, the Swift compiler, because of genericity, type safety, non-nullability, and other traits of the Swift language, the Swift compiler has access to more information than the Objective-C compiler. On the other hand, the Swift compiler is a tad little bit newer than the Objective-C compiler,
48:42
and so you can absolutely find on Stack Overflow these pathological cases where someone goes and implements a sort algorithm in Swift and in Objective-C, and it's 28 times slower, and that means Swift sucks and there's no hope. There is a switch that you can turn on
49:01
in the Swift compiler, which essentially includes unsafe optimizations. For example, around accessing arrays, so you can go outside the bounds of arrays, which adds performance at the expense of safety. You can choose to go that route, but looking forward,
49:20
absolutely yes, the Swift compiler from a compiler perspective has more information, and so it is capable of producing higher quality code. I'd say for, I mean, I obviously haven't ported every single iOS application to Swift, but I find it unlikely that you'd hit a serious
49:40
performance issue not in a benchmark. Just remember there's projectors, and so I can just barely see silhouettes, like ghosts in the audience, so if you still have a question, try to make it obvious.
50:00
Oh yeah, okay. Yeah. So this probably is going to be the last thing we do, but yes, so basically where is that other project? Can you switch back
50:22
the screen? Thank you. Right, so we had this call here to open URL, and I'm not connected to the internet, but open URL is a method that takes a non-nullable URL.
50:41
You have to give it a real URL, it doesn't accept null. Now, NSURL, what I'm doing here is basically constructing an object of type NSURL. The NSURL constructor that we're calling here, which takes a string and converts it to a URL, that constructor might fail by returning null. This particular
51:02
constructor might be other constructors which can't fail, but this constructor is designated to return a nullable NSURL. So the constructor returns a nullable thing and the open URL method takes a non-nullable thing, and this is actually a good example of how the type system protects you. So in Objective-C, you would
51:21
call open URL if the NSURL constructor returned null. Now here, I have to tell the compiler my intent. I can either test, you know, construct an NSURL object, take this thing out, and say if let URL
51:40
equal this whole thing, then open that URL. So I can either be explicit about my test, or, and that's the thing I did in this other project over here, or I could use the unwrapping syntax. And this tells the compiler I know what I'm doing, so
52:01
I'm guaranteeing it's not going to be null, and so this converts the type of this expression from a nullable expression to a non-nullable expression, and if that thing ends up null at runtime, it will crash. But since, you know, I see the shape of the URL, I'm just assuming it's going to be okay. So, either way, you have both ways,
52:22
right? You can unwrap by telling the compiler I know what I'm doing, or you can test explicitly. So that's actually a good illustration of the whole optionality thing. Yeah. How what? How easy it is to work with REST services? Again, unfortunately,
52:41
a question not about Swift, but about the whole iOS ecosystem. It is pretty easy. There is some really great libraries. Apple has a really nice library called NSURL Session, which is pretty easy to use, but there's great, there's other great frameworks for this as well.
53:01
Well, if anyone has any extra questions, would like to discuss Swift a little more, again, please feel free to approach and ask, and I have another talk on .NET application performance, actually. If you'd like to come, it's going to be in room 3 in 25 minutes. So, thank you again for coming. Enjoy the rest of NDC. Thanks. And don't forget to
53:23
vote.