Sessions is temporarily moving to YouTube, check out all our new videos here.

A Swift Detour from JavaScript

Zahra Traboulsi speaking at Front-End London in May, 2017
495Views
 
Great talks, fired to your inbox 👌
No junk, no spam, just great talks. Unsubscribe any time.

About this talk

JavaScript is eating the tech industry - including mobile development. So why has Swift only increased in popularity since its arrival in 2014? In this talk, we'll compare and contrast Swift with JavaScript: from syntax basics to paradigms to language features you never knew you missed and finally, considering Swift's place in a JS-dominated world.


Transcript


- Hi, everybody. As has already been said, I am Zahra, and just in case you haven't noticed from the company slide deck, I am a mobile developer at Bloomberg LP, just around the corner, quite near Earl Street. So today I'm here to talk to you about Swift at Front-End London, and I've already had a few people come up to me and asked me why this is in Front-End meetup like, "Yeah sure, I'm interested "but it's not exactly relevant," right? The thing is as time is going on, JavaScript is becoming more and more pervasive. We're seeing front-end skills being used in all sorts of different fields, not just front-end where it was already traditionally seen as being used. From day to day, I work on the mobile team so while I am an iOS developer, I do do a lot of server-side work as well, and that includes using JavaScript on the server side as well as Python and other languages but I do spend a lot of time using Swift and JavaScript, and actually I've not been an iOS developer for long. I only started learning Swift about six months ago just for my job because I started off as a graduate not knowing necessarily where I was gonna end up, and I was always very interested in front-end itself so I thought with all of these conversations happening about bringing JavaScript to mobile be it through progressive web apps or be it through frameworks like NativeScript and React Native, I think people aren't really informed about the other side of the table so much. Swift developers don't know much about JavaScript, and they don't really want to know a lot of the time, and it's the same with JavaScript, and talking about Swift so I thought, "Hey, this is a good opportunity "for me to level the playing field a little bit," have everyone be a little more familiar with what's going on on the other side of the table, and more open to conversations about using potentially different frameworks or even a combination. So what this talk is gonna be, I'm not gonna talk to you about how to architect the perfect iOS app. To be honest, I have no idea. I'm still really a novice myself when it comes to that sort of thing but what I do know is what it's like to learn Swift as someone who really enjoys JavaScript, and all of the things it lets you get away with as a loosely typed language. I'm gonna start off from the start. Let's have a look. We'll start off with variables. We've got our common methods of assignment. We've got var, we've got let, and we've got const. Var and let, pretty much the same except for scoping. Var is function scope. Let is block scope. And const is a new addition from ES6, which is really welcome in my eyes because while I do like to be a little bit fast and loose with my JavaScript code, that can get really confusing occasionally so it's really nice to have that added in. So let's have a look at what Swift looks like compared to this. This is some pretty typical JavaScript code. Now we have Swift, and actually I've used the exact same code from JavaScript, and it does work for the most part. We do have var in Swift. That's how we declare our mutable variables but then actually let is immutable, and this is quite similar to a lot of other languages and JavaScript. According to Swift, I'm not gonna be ageing, which is pretty frustrating but unfortunately untrue. Next up, we've got types. I've just got a lot of words up here but really what I'm trying to say here is while JavaScript is loosely typed, it does have a lot of really interesting things going on with types in comparison to other strongly typed languages like Swift so we've got our typical and primitive types like strings, booleans, we've got number instead of int and double, which can be fun sometimes, not really, and we have a few more too but really what is interesting for people coming from strongly typed languages is using null and undefined. What's the difference between null and undefined? Undefined is just exactly that, undefined. It's never been defined. It's never been a different value. Null is potentially like something that has been a different value, and then changed to null, and probably gonna cause a lot of problems for us down the line if we're not careful, and there we go, and then we also have our basic collection types like objects and arrays. On the other hand, Swift, while it does look a lot like JavaScript, and it is typed, and you'll notice in the previous slide, there weren't any type signatures. Actually it's got really great type inference so most of the time when you're dealing with variables, you don't have to worry about declaring the type at all unless it's something that's a bit ambiguous. It has a really fantastic type inference there so it's very easy to get started writing typed languages, and as I said with JavaScript, it's got very similar types. We do have a different type of numbers, which can be very helpful. I do enjoy that. And instead of null and undefined, we have nil, which I don't think I've ever seen in anything that isn't an Apple-based language but there we go. They just want to be a bit different, and that's fine. And when it comes to logic constructs, instead of objects, we have classes and structs, which I'm gonna be covering a bit later. There's some fine detail that separates the two. And as well as that, we have collection types like arrays, dictionaries, tuples. They're all fairly simple, and nothing that are particularly uncommon in other typed languages so there we go. Okay. But the really cool thing about types in Swift are this new addition, which wasn't in Objective-C, called optionals. An optional is essentially a wrapper around a type, which will make sure that that optional type is either the type that it wraps or a nil, and this comes really handy when you're dealing with, for example, UI code because you're gonna be querying with a, say, the user's input or something so you want to get the value out but maybe they haven't put anything in yet, and the way Apple tended to work with nil values in iOS as a whole is that the preferred behaviour for dealing with nils was to just crash the app because you don't want to be using an app, and seeing any undefined behaviour, right? You just want it to crash so crashing is good. Don't tell my manager I said that. For example, I have illustrated the typical British bus stop to get this over. Here we have a function so we started off with func, a little bit different but nothing unexpected, and we've got our function getBusAtStop, and this means that it's going to return an array of buses possibly. It's an optional array of buses essentially so it will return either an array of buses or nil. We're gonna programme what we think bus timetables work. Right. Okay, we've got a chance of 100, one in 100 chance, and let's be a bit optimistic. Let's say there is a 33 in 100 chance that a bus is gonna turn up at all so if there is a chance that a bus is gonna turn up, obviously three buses are going to turn up because that's just how it works, right? Otherwise we're not going to return anything because this is just the bane of my existence so just to have a look at how we can interact with this a bit more. So to access the value inside, what you can do is one of two methods. You can either force unwrap your optional by adding an exclamation mark at the end, which does make it look like you're slightly emotional when you're writing code with this language but there we go. If you've force unwrapped a nil, you're going to crash most of the time. A safer option is to sort of tentatively ask whether this is actually wrapping a real value or just a nil so what you can do is if let, and then you give like a new variable, and you say, "Okay, maybe this is gonna return something "that isn't nil, and if it is, we'll put it in there," and this is some optional code that you can put in to deal with that new value that you've just unwrapped, and in this case, I would just gawp because a bus turned up, and not actually remember to get on it so there we go. Okay. Next up, we've covered types. We've covered the primitives, and we've got optionals, and now we want to get on to logic constructs like classes so in JavaScript ES6, we do have classes. In traditional JavaScript, we don't. We have object and prototypal methods but now we have some nice syntactic sugar to cover that up so what you can do is you can define a class so I've got a class programme there, and if you're a JavaScript programmer, obviously my favourite language is JavaScript, I go to write everything in JavaScript, you're gonna do some coding, and that just returns some of the strange intricacies of that language so it will return null is not equal to undefined. In Swift, it does actually look very similar. You've just got to make sure you declare your types for your return so we've got func code here, and that returns a string just like code it did in JavaScript class, and we've got butDoesIt Float equals yes. This is actually a code that you can compile. It works. Sometimes I look at Swift with all of the punctuation, and I'm just a bit like, "I can't believe this works," but there we go, and obviously you've got your favourite language if you're a Swift developer, which is Swift because everyone loves their favourite language, right? Those are classes. Let's take another look at, a closer look at classes in Swift should I say. We're gonna define a Sheep class. The sheep, it's got a name, it' got an age, and we've got an initializer here. In classes, you do have to define your initializer. They don't come for free. When we initialise this sheep, we're gonna give it the name, and we're gonna give it its age, and let's see how we can use that, and what happens with that. I have used possibly the most cliched example in all of programming for this but here we go. Okay. I'm gonna guess that everyone knows about Dolly the Sheep clone, right? Okay. Let's have a look at this. So we've got another sheep that we're defining first. We've got sheep, its mom, say she's six years old. Okay so we're gonna clone mother. Dolly equals mother. That's gonna copy it, right? Cool. Okay, that is still sheep. Fantastic. And we're gonna make sure Dolly is zero 'cause Dolly is just being blonde, and Dolly's name is obviously Dolly. So when we come down here, we track what Dolly's age is, and actually this section is from Swift playground, which is a really cool feature that they introduced in Xcode, this is a bit on the side but I think it's worth mentioning, one of the really cool things about Swift compared to Objective-C is that it can take extremely long time to build those languages especially if you have a code base as large as ours but what Swift has are these things called playgrounds so you can quickly write up pieces of code, and see how they're gonna compile, and what the results are gonna be so that really improves your quality of life for development. So here we've got Dolly whose age is zero. Okay, that's expected. We've got Dolly's name, which is Dolly. Now the mother's age is zero. What? And the mother's name is that. What? What's going on here? This is not what we expected, right? Okay. A bit weird but let's see if we can solve this somehow. Let's try using a struct instead. As you'll notice, it's exactly the same code. We just changed the keyword in the top here from class to struct. Let's see how that pans out. Exactly the same code again but this time, we get what we expect. The sheep is being cloned but it's got different attributes that we've given it, right? That's what we wanted in the first place, and why is this the case? Classes and structs in Swift are very similar. You can use almost exactly the same code but classes are passed by reference so when you say clone a class by assigning it to another variable, in that case, it doesn't actually make another sheep, it just creates a reference to the existing sheep that you had define in the first place whereas in struct, those are passed by value so really when you clone a sheep, you have a new sheep, two independent sheep. That's good for familiar bonds, and the thing is structs also have some other cool tricks. The first one that is actually quite relevant to this is that structs are copy and write so while I say we do have two independent sheep, a really cool optimization that we have is that if you do sort of clone the object or the struct should I say, it is actually a reference to the same object originally like a class but as soon as you write to that new variable, it actually creates another struct so we don't waste space if we don't need to. We have one object until we need to change it, and that's a great optimization especially when you're getting into a really large code base, and as I mentioned earlier, your initializers and classes don't come for free but you can get a default initializer for structs so if you don't define any initializers on your struct, then it'll just give you a memberwise initializer, which means it'll just have a free initializer that you can define all of your class' variable or struct's variables in to start off with. Okay. So we've had a look at some of the sort of constructs, and the basic building blocks of your programmes that you're going to run in Swift but we know that really what we love about JavaScript is that it's multi-paradigm, right? If you feel like writing object-oriented, you can. If you want to write some functional code, you can. If you want to write some imperative code, you should probably use Python but yeah, why not? And it's the same as Swift. Swift is equally multi-paradigm. We do have the same ones here, and we do have functional programming, and functional programming is currently a really, really popular topic in Swift. So let's have a little bit of look at that. I'm not gonna delve into it too deeply. So I'm not gonna go into functional programming right now because this isn't a functional programming talk but I'm just gonna say that JavaScript and Swift both provide map, filter, and reduce functions, however, Swift has a cool little extra inspired by languages like Haskell. Here we go. We have flatMap. What is flatMap? flatMap is essentially exactly the same as map, which will apply a function to every element in an array that you have except it applies that to arrays so this is really useful for dealing with nested arrays, which do come up occasionally. So here I've set up a flatMap where we're getting the minimum from each array, and what this returns is one array but with a minimum of each array that was in our original array. What else is this useful for? Surely there could be something else we could do with this, and it's actually quite useful for dealing with optionals so this isn't something that's particular well known but it's been overloaded so that if you have a list including some optionals. So I went up to Edinburgh for a couple of days the other day, and before that, obviously living in London, I had no idea what fresh air and animals were but here we go, we have a listOfUnknowns, and now we're gonna generate my listOfKnownsPostTrip so we're gonna just apply a flatMap, and actually what I should mention is this dollar zero just means your first argument that you're passing in but obviously with functions like map, filter, and reduce that's acting on each element in your array so you only have one variable really. So here we've used flatMap, and suddenly the nils have disappeared, and this is a really handy trick for just getting rid of your null values, null values, your null values. So this comes in really handy because you do end up using optionals quite heavily in Swift, and this is something that you can use. Okay so we're back to paradigms, and you'll notice that we've added a new one to Swift, and this is protocol-oriented. Apple like to describe Swift as not being object-oriented but protocol-oriented, and what does this mean? And this is actually a really cool part that I'm quite excited to talk about. Protocol-oriented programming defined is revolving around protocols. I have a couple of examples here. I have a protocol CanFly, and that has a maximum flight speed so the way protocols work is they're essentially descriptions of something, and these are things that are applied to your types like your classes and your structs so we have a protocol CanFly, and a class or struct will obey this protocol if it has maxFlightSpeed, and obviously we have CapeWearer, which is another protocol, and we have defined that if you are a cape wearer, obviously your cape has colour, and you have a size that you need your cape to be, and these sections here get and set define whether it's read-only or whether you can read and write those variables. Let's see this in action. Okay. Is it a bird? Is it a plane? No, it's Superman. So here, I have conveniently forgotten to add the protocols into the first two examples but let's just pretend I didn't do that. So imagine here I had CanFly applied to these two classes so they both obey the CanFly protocol so they both have a maxFlightSpeed but obviously Superman wears a cape so he also has a maxFlightSpeed but he has a cape colour and cape size as well, and this is gonna bring me on to what the benefits of protocol-oriented programming over anything else. So some people who might work with Java or something like that in the past might think, "Isn't that just an interface-based programme?" Paradigm even. No, not really. Actually this was also used in Objective-C, and that was kind of what Objective-C's version of protocols were like. You just had a lot of protocols, which were very interface-based. They were very specific to a certain type of class, and not really anywhere near as flexible as these. So the good things about it are it encourages composition over inheritance. So rather than inheriting from things like you would in object-oriented programming, it would encourage you to use composition so it would encourage you to use multiple protocols to build up your class or struct using protocols from multiple places, and not to waste time writing code that's only applicable to a few things, and this is what I'm saying here. Imagine for example to carry on is a metaphor but birds and planes really aren't similar in any way other than they both fly, right? So say you're writing a programme about lots of things that fly like I apparently do in my spare time, you wouldn't really imagine having a super class that both bird and plane could inherit from so imagine you'd be writing a super class for those classes, and you think, "Okay, they can both fly "but they're not really similar in any way "so I'm gonna end up having to duplicate "this flying code into both of their super classes," and that's just a bit of a waste really because you've written it once, why write again? So that's a nice way to compose your classes. Just the last feature I'm gonna cover from Swift today. These are extensions. I'm gonna be honest. I don't fully understand them myself yet and I don't think many people really do get where and when is exactly appropriate to use them all the time but they do offer a lot of great benefits. What they're described as by Apple is I did this one on my own so extensions add a new functionality to an existing class, structures, enum, or protocol type. I've got an example here. Working around shu-dich, I just have to get my daily dose of hipster, right? And what's the point in speaking if you can't speak in hipster brand names? So I'm gonna add an extension to the string type because I think this really needs to spread everywhere, right? I can't just apply it to my own classes so I've added a new function called hipsterify, which could quite easily be an awesome name, and it's gonna return a string, it's gonna return itself. Here what I'm doing is I'm taking all of the vowels out except the A, which I'm replacing with a V, and I'm making it capital letters, and honestly, this was inspired by me just seeing people's cats walking around. That seems to be a very popular thing to do. I've seen it so many times. It's quite strange. I'm interested to see how this trend is gonna evolve but we'll see. The code in the middle isn't too important. I'm just replacing things, and I'm actually using filter, which I missed out earlier but then again so what happens is that we now can use map for example. We're just working with strings so these are all very normal strings. They're not my own class. I haven't defined them. It's just standard but what I can now do is I can call this method on them that I previously couldn't but I'm gonna be honest, I don't know who else would think of this except me but there we go so I can map those onto strings now really naturally and comfortably, and nobody else has to deal with my nonsense, which is quite nice. That's one example. We've got our new hipster brand names down here. If anyone wants to take them, I won't chase after you for copyright reasons or anything like that. So yeah. My point here is that it's a really nice way to add functionality to something that you might not have had access to previously so say, you're working with someone else's framework or module, and you want to incorporate that in your code but you're like, "Ah there is just this one tiny feature "that I'm missing but I really need it "so I can't use this entire framework" so if someone has done 90% of the work for you, it's much easier for you to add that extra 10% yourself, and really tweak it to your needs using extensions, then it would be to spend so long searching for the perfect framework that someone else has written. It's really a matter of convenience. Yep, that's the large major Swift feature I'm covering today. Just to give you a little sense of where the Swift community is at, it's been a year since Swift has been made open source, and there has been really great engagement in the community, and a lot of discussions online, lots of conferences like I can barely believe anyone talks about not going with the Swift in the future, and it's been three years since the language was announced by Apple, and there has been three versions, and it's been getting better and better every time. The thing is, and this along with Objective-C are still the only languages really used exclusively on Apple platforms. You won't really find it easy to use JavaScript on things that aren't iPhones to be honest, and it does face the challenge on mobile, React Native, and I know myself and some of my colleagues in the audience have really been pushing to try and integrate a bit of this into our code base but honestly it does have a time and a place, and server-side Swift is in the making as well so you might see it there but really what I want to say with regards to Swift in comparison with JavaScript, they're two different languages. JavaScript is perfect for prototyping, and if you're really into your JavaScript, you'll have a really good grasp of maybe all of these frameworks coming around like flow and type scripts to add types to your JavaScript but if you're coming into the industry as a beginner, or if you're looking to make a move into front-end or mobile development, it's much easier to start off with a language that places those restrictions on you to write good functional code at the beginning so it's really a matter what's going on with you. So if you have a team of Swift developers, and you think, "Oh React Native is like the hot new thing. "Maybe we should have a look at that. "Maybe it will make us reduce the size of our teams early." I don't think that's exactly the best ideas at the moment because while React Native is great for apps that you may need to develop quickly, or you may need to, yeah, you may need to develop quickly, or you may need to develop as a one-off. That's a really good choice but as someone working in a team of like 70 developers, Swift really does helping in terms of placing those restrictions on you, and having that levelled playing field in terms of knowledge of things that are restricting you in writing good code. So yeah. I hope to see more hybrid JavaScript and Swift ops in the future. All the code used in this best place. But yeah, that's me. Thanks for humouring me. Any questions? - [Facilitator] Anybody have any questions? How about Swift? Does anybody in the audience use Swift? One guy. - I brought him with me. - [Facilitator] Sorry? - I brought him with me. - [Facilitator] All right. That doesn't count. So a user on the Bloomberg app. - Yeah, we do. It's quite a large app, and people ask me, "What are you, "rewrite it in React Native," it's like, "No, that's gonna take years." - [Facilitator] Do you have an Android version as well? - We do. I'm actually an Android user so. Ironically. - [Facilitator] Is the Android team 70 developers as well? - It's the mobile team in general. It's probably slightly under that but it's a very large app, and some people joke it's slightly more like an operating system but we have a lot of functionality to pack in there, and it's very important that we get it all right. - [Asker] I'm just trying out with learning JavaScript. Is there any advice or resources that you could point me towards if I want to learn JavaScript or Swift at this early stage of mine? - Oh wow. Okay so how familiar are you with just general object-oriented programming? - [Asker] I don't know what that means. - Okay, awesome. That gives me a good place to set up. I think one of the really important things to think about as a new developer is actually starting to think about and thinking in terms of concepts rather than languages especially with learning JavaScript for the first time. It's very easy to get used to the things about JavaScript that are very unique, and think those are quite standard whereas maybe it isn't, and I would recommend just having a look at a couple of different languages, get familiar with concepts like maybe object-oriented programming. Some people disagree with me, and say, "That's a thing of the past," but I don't think it's going away just yet so focus on concepts like classes, objects, and writing types for example. That's not something you'll necessarily do in JavaScript but maybe try out Python, things like that. Honestly, there are so many great resources on the internet I can possibly, I can't even begin to think which one to recommend but actually tweet me later, and I'll send you some links. - [Asker] That was a really, yeah, really help explanation of optionals. I'm trying to work out is the handling of optionals, they almost look optional. - My point really is there is a couple of ways to deal with them but the point of them is that you're generally going to actually need to access the value inside at some point. You can't really continuously handle optionals until you get to the end of that process like there is some point where, so for example I had a string input where I put in my address for example or I didn't, you don't know so at some point, you're gonna need to pass that data back, and you're gonna need to figure out is it nil, do I need to do some validation on this field, or you're gonna say, "Okay, I have the address, "and I'm gonna send it in my request to the back-end now." So I get what you're saying but there generally does come a point when you need to unwrap the optional. Yeah. - [Asker] I'm really convinced of how useful something like optionals are. - Yeah. - [Asker] But in your code with the buses, you kind of have-- - Oh okay. - [Asker] You could almost have an optional but just say, "I'm gonna pretend it's not an optional," and let your code crash. - For example, that would be in a sort of situation where you would strongly expect to get that value, that you would strongly expect it not to be nil but there is a chance that it might not, and then you would want your app to crash instead actually because then you'd be dealing with some undefined behaviour or something like that so it's generally safer to do the second option but there's cases where you're like 99% sure that you're gonna have that value, and it's going to be actually something very wrong with your programme if you don't have it so that's the sort of place where you use it. - [Asker] That's perfect. Thank you.