with Simon Allardice
The first iOS programming alternative to Objective-C, Swift is a clean, accessible, object-oriented language, with built-in support for modern programming features like closures, generics, and tuples. The main stumbling block for new Apple developers has always been the Objective-C language, which many developers find overly complex.
Here Simon Allardice explores Swift’s core syntax—variables, data types, functions, and control structures—and its object-oriented classes, via playgrounds, the innovative coding interface that allows you to see the results of your code instantly. He also introduces key concepts that lie at the heart of Swift and the best practices that are already developing around it. Plus, learn how to take Swift further, with advanced operators and features like protocols, generics, and extensions. Whether you’re looking for a new language or for a place to enter the iOS/OS X development world, you’re going to love Swift.
- Installing Xcode 6
- Writing Swift code in playgrounds
- Declaring variables and constants
- Defining functions
- Working with complex types, including arrays, enumerations, and closures
- Creating classes
- Defining advanced properties and property observers
- Working with generics
- Supporting protocols
- Adding functionality with extensions
Table of Contents
- Introduction 4m 40s
- Welcome 1m 47s
(chimes) – Welcome. This is SWIFT Essential Training. I’m Simon Allardice.SWIFT is Apples new programming language for creating IOS and Mac applications. It’s the first time we’ve had a real alternative to the older Objective-C language, which a lot of developers found challenging or unintuitive. In this course, we’re going to begin by getting the necessary tools, which is simply thelatest version of Xcode, and jump immediately into the core syntax. Working with variables, data times, program flow, functions, even in that simple code,we’ll start to encounter some very specific ideas that Swift is build on. At the same time, we’ll be exploring Xcode 6 using a new feature of Xcode playgrounds. To instantly see the results of the code we write, without explicitly compiling or even running that code. Now, Swift is an object orientated language, so, we’ll cover how to define our own classes creating objects with methods and properties. We’ll talk about modern language features that were never able to be part of Objective-C, like, (tuple’s), and optional’s, and go all the way into more advanced topics including, generics, protocols, and extensions.Through all of this, we’ll stay aware of the best practices all ready developing around Swift and ways to make it memorable. So, it’s natural to write. If you’ve been meaning to get started with IOS or Mac development, you just never got around to it, well now is the perfect time to start. Swift is the perfect language to start with. If you’ve all ready spent some time in this world, you’ll find you’ll be able to take the concepts and ideas that you all ready know, you just know have a clearer and more focused language to use them with. Even if you’ve been working in Objective-C for years, there were just things about it you never enjoyed, you’re going to love Swift. Let’s get started.
- What you should know 2m 53s
– Whenever I write a course, I need to begin with a couple of assumptions about you, dear viewer. I try not to have too many, but here’s the two I’m going with. That a, you know your way around a Mac, and b, you have some programming experience. That’s it. You may or may not know Objective-C,you may not have done any Mac or iPhone programming before, that’s fine,but I do expect you can write code. To make the most of our time, this course is about Swift. It’s not a beginner’s guide to programming. So at a minimum, you should already be comfortable with the fundamentals.
Variables, loops, conditions, functions, the core concepts found in all programming languages, and know at least the basic principles of object oriented programming. Terms like class versus object, inheritance, methods, and properties. Now if you haven’t programmed at all, this isn’t the place to start. Take a look at my foundations of programming fundamentals course here at lynda.com. If you’ve worked with Objective-C, I will point out some differences worth knowing, but that isn’t the focus of this course. And I don’t assume anyone is an Objective-C expert.
- Welcome 1m 47s
- Core Syntax 56m 17s
- The structure of Swift 3m 40s
– Before we jump into Xcode let’s take a look at some basic Swift code. Don’t worry about the exact syntax right now, I just want to point out a few things about the general appearance and structure of Swift. Now if this was the first Swift code you had ever seen, as a programmer you could still make a fewassumptions about this within a few seconds. That first it seems to be a C-influenced language. By that I mean we’re using curly braces to surround blocks of code, there are keywords in lowercase, like if, else, for and return.This if statement should be fairly readable no matter what programming language you’re used to.
So yes, Swift is absolutely a C-influenced lanague. We use curly braces, there are many keywords you’d recognize from working in any other C-influenced language, although as we’ll see there are also the keywords you’d expect to find in an object-oriented language like class, private and public. But there are keywords you might not be familiar with perhaps like func here, although you could make a good guess at this and there are other keywords that are specific to Swift. And we will of course go through all of these, but while Swift is C-influenced it is not shackled or handcuffed to C.
Unlike the Objective-C language, Swift does not attempt to be C compatible.As Objective-C developers will know, you can take a section of old-school C code from 1970-something and paste it right into an Objective-C program.Now you try that in Swift and all you will get is a screen full of compile errors.Swift is its own language, it’s not a superset of something else. So what other similarities do we have? Well we do indent our code in Swift as you can see,but indentation is just for readability. Unlike say Python, indentation in Swift is not meaningful in itself though there are some things I’ll point out about whitespace shortly.
Now comments are as you might expect in a C-influenced language. It’s just // to begin a single line comment and multiline comments would begin with /*and end with */, but while there are many similarities Swift also immediately gives us some key differences from most C-influenced languages. First, Swift statements do not need semicolons at the end. Notice how I’m saying this, you don’t need semicolons. You can have ’em, it won’t cause an error if you put a semicolon at the end of a statement.
That’s what the style guidelines will recommend for various reason including some pesky bugs, so know that in Swift this does not apply. The standard practice is you do not write semicolons. Apple’s own sample code does not use them, end sidebar. The next difference is that unlike many C-stylelanguages we do not need a main method or a main function to say where a basic Swift program begins. If I just wrote some Swift like this and ran it, it would start at the top and work its way down. And sure as we get into more complex applications spread across multiple code files we will want to control the entry point and we can certainly do that, but we don’t need a main method for simple Swift code.
And that leads us into the next question, well how do we write and run a simple Swift program? Up next.
- Writing Swift in playgrounds 7m 6s
– As a programmer, not just in the Apple world, but in Windows or Linux development too. If you have an idea and you just want to write a few lines of code, well you often can’t. You can’t write a few lines of code. You have to create some structure for it first. That often means creating a new project in your IDE whether that’s Xcode or something like a clip or visual studio.Another, create a folder somewhere, perhaps with some configuration files and spawn up some default classes and boilerplate code. Maybe a user interface. All just to allow you to finally write your few lines.
Most developers end up with dozens of tests something, something projects all over their systems. Okay, not a huge blow back but another speed bump.With Swift, we don’t need to do that. We can use something called playgrounds. Playground is a new feature in Xcode six introduced for the Swift language. There are new document type. A Swift playground is a self-contained single file, not a project. That’s kind of the point. It lets you quickly write some code and test that code without all the overhead and wait what becomes with the project.
But it’s not just about having a quick way to write code. What’s unusual and different about playgrounds is it continuously show you the results of your Swift as you are writing and changing it. They automatically execute and refresh all the time. They’re great way to experiment with Swift and to learn it.In this course, we’ll use playgrounds rather than creating entire projects in Xcode. When you open Xcode six, the first option on the welcome screen is to get started with the playground. Although you can use this option, you can also create a playground from the regular file menu in Xcode.
Either way that you choose to do this, I’m going to ask you if you want this playground targeted at iOS or OS X development. All this is going to do is link to the typical frameworks you’d need if you’re writing either iOS or Mac applications. Now for us in this course, it doesn’t matter at all. We’re focusing on the Swift language itself, not on user interface stuff. So I could choose either. I’ll just leave it at iOS and click next. Then we’ll just save this somewhere, anywhere. It doesn’t matter. There’s no magic location for playgrounds. I’ll save mine to the desktop.
The font is a little small so I’m going to make one quick change to Xcode. You don’t need to do this but I just want to increase the size of it so it makes it easier recording this course. A new playground by default appears with two sections. A code editor section on the left and the results pane on the right.You can drag the bar in the middle to rearrange the proportion of this. There is a third section to playgrounds called the timeline which we’ll see in a moment.But what you won’t see when a playground opens is the usual project settings, project editor, configuration options, toolbar, etc, etc, etc, that you would usually get in a typical programming IDE because, although Xcode can certainly do all that, again, this is simple.
This isn’t part of a project. This isn’t a part of anything. It’s just a standalone Swift playground file. We write our Swift code and it’s a little here provided by default. As we write it, we’ll immediate see the impact of that code appear in the results pane on the right hand side. That’s without explicitly running it or compiling it. So I’m going to leave the default code here and just create a simple variable. Var highscore equals 100. It’s going to show me immediately the result of this expression is that high score is 100.
I then decide to add something to this. Add 50. It’s going to recalculate that.I’m not hitting any keys here. It just shows me that it’s 150. As I’m typing, you’ll see the text in the results pane will flicker between grey and black. That’s because as we add and change code, and if I change this, say to 99, it’s going to update and recalculate and reevaluate itself to make sure the results are all still correct. So when the results are grey, what’s happening is the playground is recalculating. When it’s finished recalculating, the results are shown in black text.
If you make it change and the results on the right hand side are still in grey, then there’s something wrong with your code and the playground can’t figure it out. Now not all code you write will show you individual single values on the right hand side. Let’s say I add a simple loop. Again, don’t worry about the exact syntax yet. We’ll get to that. This loop is going to iterate a hundred times, incrementing an index called i and adding the current value of that to our high score variable. So the results pane just shows me here that this happens 100 times.
Well, this is pretty good. At a glance, I can tell if I got an off-by-one or a fencepost error but it’s not showing me the actual value of this high score variable and how that is being changed inside the loop. But if I mouse over this line in the results pane section, I’ll see two icons appear. This one’s called the quick look icon, the eyeball. We’ll get into this later. There’s also a circle with a crosshair called the value history button. If I click the value history button, I will see the third section of the playground appear called the timeline.
We just rearrange this a little bit so it’s easier to read. The timeline is going to generate a chart which shows the changes over time that come from this statement. The addition to the high score variable inside the loop. Well not only this but there’s a slider at the bottom of the window and I can drag this to simulate going back and forth through the iteration of this loop and seem how the value changes for everyone. This can be extremely useful when you’re diagnosing loops that aren’t doing what you’d think they should be doing. Now having said that, I don’t always need the timeline.
If I simply wanted to know the final value of this high score variable after the loop has finished executing, I can easily get to that too. I’ll close the timeline down. Just go back to the regular view here. Now to write a line of a Swift to spit out the value of a variable, you might expect that we need some kind of print statement or a console statement or log statement. But in a playground, we don’t even need that. The simplest way to see the value of a variable here is just to write the name of this variable on its own line.
I’ll just write high score. Because as far as the playground is concerned, this is just a very simple expression and it’s going to evaluate that expression and you’ll see the results over here in the right hand side. The current value of high score. So notice, we’re not just seeing the final result. We are seeing the values change over time without writing any logging statements, without even explicitly executing this code, and, as a playground, is constantly updated. I can make a simple change. They, back up at the top. Change this one to 999and it will immediately trickle down and show the resulting effects on the rest of the code.
So they’re a fantastic interactive way to learn Swift. Even after you’re comfortable with it, they’re great way to experiment and develop ideas. You can always take code that you’ve written in a playground and put it into a moreformal project later if it’s useful. All right, there is more to playgrounds but this is certainly enough to get us moving forward into the core syntax of Swift.
- Declaring variables 8m 38s
– The first thing we’re likely to do in any programming language is make a variable. So let’s start there. In Xcode, I’ll make a new playground. I’ll call this Variables and save it on my desktop. There’s an example in the default code that, in Swift, we use the keyword var to declare a variable. It’s the word var, all lower case, and then our variable name. The suggested naming convention, as in many languages, is that variable names are camel case,using a lower-case first letter. But I am not finished. I’m going to give this variable an initial value.
Sometimes you use var and sometimes you don’t. So let me be clear here: when we make a variable in Swift, we use the keyword var to do it. It is not one of the options for declaring a variable, it is the only way we declare a variable. Every variable in Swift is declared with the keyword var. (with rising volume) Let me say that again. Every variable in Swift is declared with the keyword var. End sidebar. So we move on, and I’ll declare two more variables,also giving them initial values.
As you can see from this, string values are surrounded by double quotes, and those of you coming from Objective-C will be glad to see that we no longer need the leading @ sign in front of a string. We also have Boolean, which can be true or false. Again, for those of you coming from Objective-C, that’s true or false, as opposed to yes or no. Now, if the first Swift you ever saw was justthese few lines of code, all using the word var, but with different types of values, you would be forgiven for thinking that, perhaps, Swift is an un-typed,or at least a loosely-typed language, that it doesn’t seem to matter what kind of value a variable holds.
Maybe it’s a string; maybe it’s an integer; maybe it’s a Boolean. Well, I would forgive you for initially thinking that, but you would be barking up the wrong tree because Swift is a type-save language. It is strongly typed. All variables in Swift are of a specific data type. The variables are integers or they are string variables or Boolean variables or arrays or some custom object, but they are something specific. They are something in particular. So what’s happening here is that, when you write simple code like this, Swift will do what’s called type inference.
So if I’ve declared some variables and Swift has inferred their type, that firstName is a string, and then, later, I add another line of code like this, I would expect to see an error because I’m now trying to treat firstName as an integer. And we’ve got this exclamation mark appearing on the left-hand side, and also, all the text is showing up in gray in our results pane, which is a hintthat Swift cannot evaluate this playground properly. If I click that, we see the error message. It’s not the friendliest one in the world: “Type ‘String’ does not conform to protocol “‘IntegerLiteralConvertible’,” basically saying, you can’t take firstName, which is a string, and treat it like it’s an integer.
It is not going to implicitly convert an integer value into a string value. It won’t do that. Now, there are all sorts of options for explicitly converting values from one type to another, but it won’t just happen automatically. That’s a safety feature of Swift. It’s not going to implicitly change one thing into another kind of thing. “But,” you might be wondering, “what if I don’t, or can’t, “provide an initial value for Swift to infer? “What if I want to declare a variable and then, later, “set its value?” Well, that’s fine, you can do that.
What happens is, if you write a line of code like this, var myVariable, and there’s no initial value, then Swift cannot infer a type because there is nothing to infer. That’s okay, but it means that this code, by itself, is not enough. And if I try and leave this alone, I’ll see that I’ve got the exclamation mark showing up over here. It would also give me a compile error if I was writing this in a proper project in Xcode. And the error would be that “Type annotation is missing.” Swift is saying, “I don’t know what this variable “is supposed to be,” because, when we declare variables in Swift, either we provide an initial value so that Swift can easily infer the type, or, if we don’t do that, then we must say explicitly what the type of this variable is.
And we do this by writing a colon after the variable name and then the data type we want for that variable. So I’m going to ahead and make this an Int.This is now showing up. There’s no exclamation mark on the left and all the text is showing up in black. So it seems that Swift understands this code just fine. So this is called the type annotation, the colon and then the data type.Think of the colon as meaning ‘is of type,’ so myVariable is of type Int, and Int being the classic Swift integer data type.
Now, this point is where some tutorials would go through a big list of all possible data types and their sizes and ranges. I’m not going to do that here.We’ll talk about some of these in more detail later. But I’ll leave some of the specifics as an exercise for you. For now, know that straightforward data types include Int, for integer, Float and Double, for 32 and 64-bit floating point types.We have a very powerful string type. There’s also a single-character type, and there’s the Bool with, again, true or false.
And notice that all the types here, which are showing up in purple — they’re color-coded in Xcode — they begin with an uppercase first letter, even the simple ones like Int. Now, there are, of course, more complex data types we can use. There are collections, like arrays and dictionaries, or custom objects.We will see these all later. Now, if you want to be explicit about the data type,and also provide an initial value, I could certainly go ahead and do that. Say you’re creating a variable called lastName, saying it’s a string and giving it a value, or saying it’s a Boolean or an integer and giving those specific values, as well.
I’m getting a complaint here about this variable, just because it already exists here. Cannot put the (mumbling). I’ve declared it twice. That’s not going to work very well. We’ll change that and then let it go ahead and update. This is perfectly acceptable code. So, var lastName, the type annotation, and then the initial value. But if a value is so obviously a string or so obviously a Boolean or so obviously an integer, there is simply no need for the type annotation. These are optional pieces.
You can remove them if you want to. So let me clear up a misconception. The point of type inference in Swift is not to try and obscure or hide the data typesfrom us as programmers. It’s quite the opposite. It assumes that, when we write code like this, we deeply understand what our data types are. Type inference is simply there to make code more concise and more readable. So if the data type is blindingly obvious, both to us and to the compiler, then we just let Swift infer it. But if it’s not obvious, particularly when we’re not providing a default value, as with this interestRate variable down here, then we need to provide that type annotation.
We need to say what the type is. And you will see this kind of thing a lot, that many decisions in the Swift language are to improve the clarity and the readability, but also the safety, of our code.
- Creating constants 4m 11s
– So, we just started using the Var keyword. I have a new playground here but here’s where I try and persuade you to use a different keyword. That in Swift, we favor using the keyword Let, instead of Var when creating pieces of named data. Now hang on a second, Simon, you might think. Didn’t you just say that Swift uses Var to declare every variable. Well, yes I did, and that’s absolutely true. Var declares a variable and using the keyword Let we create a constant instead. It is still a piece of named data, but once it’s been given a value, that value can’t change, it can’t vary, it is not a variable.
If I try and change it to something else, I would expect a compile error. This value needs to stay constant through the lifetime of the executing program.Other than being unable to change it, everything else about the syntax of using Var, and Let is identical. You can use one keyword or the other. Like all variables, all constants have a name, they have a specific data type. They have a value. If Swift can infer the type from the initial value, it will.
If it can’t or if you prefer to be explicit, we need that type (annotationly) colon space type name after the name of the constant. It is most common to declare a constant and also set its value on the same line, and when you’re using a playground, you always need to provide the value of a constant immediately.Later, when creating our own classes, it’s possible to declare the constant in one location and later set its value. Perhaps, loading a value from elsewhere,external data like a file or a webservice or user input, but you can still only do it once.
Unlike a variable, once you have assigned a value to a constant you can’t then change that value, any attempt to do so will cause an error. Here’s the thing, some programmers might be zoning out of it, because there’s nothing remarkable about constants. We can create them in most languages. There’s often a keyword like const, or final, or read only we use to declare one.Constants are one of those things that a lot of programmers don’t do very much. The culture that evolves around some languages means, yeah, you might be able to do them, but you just don’t see them that much. You don’t really think about them.
So know that in Swift, the use of constants is encouraged. They are regarded as important, and they are common placed. There is all ready a stated best practice to use Let wherever possible. First, it’s a safety feature. Whatever you can lock down, whatever constraint you can put in place around you code, do it. Also, if we know that we have a bunch of values that won’t change during the lifetime of the program, there are even some performance optimizationsthe compiler can do. Now, of course, there’s nothing wrong with Var. When you have a piece of data that needs to change through the life of the program,use Var and go in all good health.
You will see a lot of constants used in Swift. If you’re not in the habit of making them, make an effort to use Let for a while. It might surprise you how often your pieces of data don’t need to change once they’ve been given a value.Now, if you’ve worked in Objective-C, I want to make one explicit comparison here, that might add some clarity to this. It’s a common design patent in Objective-C to find two versions of a class, an Immutable or fixed version, and a Mutable or changeable one. So, we have the NS String which is fixed, and we have the NS Mutable String which is changeable.
We have the NS Array. We have the NS Mutable Array and so on. Well in Swift, we don’t worry about having different versions of classes. Simply put, if you declare a String using Var, you have a Mutable String, because it’s variable so you can change it. If you create a String using Let, then you have an Immutable String, it’s a constant and you can’t change it. As we’ll see, this idea works with more complex objects like collections too. We are getting a little bit ahead of ourselves. We haven’t gotten into objects yet. So, we will revisit and refine this idea later on.
Just know that the recommendation for using Let to create constants in Swift is not just for primitive simple kinds of values, it’s for everything.
- Printing values and working with string interpolation 5m 14s
- Converting values 4m 5s
- Writing if statements 4m 17s
- Using the switch statement 6m 32s
- Creating loops in Swift 5m 6s
- Defining functions 7m 28s
- The structure of Swift 3m 40s
- Complex Types 55m 12s
- Creating and using arrays 9m 17s
- Using dictionaries 9m 42s
- Understanding tuples 7m 28s
- Creating optional variables 9m 38s
- Defining and using enumerations 7m 8s
- Writing closures 11m 59s
- Creating Classes 38m 14s
- Defining and instantiating classes 5m 43s
- Adding initializers to a class 5m 52s
- Using inheritance 8m 7s
- Creating computed properties 4m 43s
- Using type properties and methods 5m 9s
- Defining lazy properties 3m 22s
- Adding property observers 3m 9s
- Understanding access modifiers in Swift 2m 9s
- Taking It Further 34m 30s
- Working with structures 8m 48s
- Using basic operators 6m 43s
- Comparison, equality, and identity 3m 24s
- Advanced operators 4m 55s
- Importing frameworks and using Objective-C classes 10m 40s
- Advanced Language Features 30m 42s
- Type checking and downcasting 6m 30s
- Using Any and AnyObject references 5m 26s
- Supporting protocols 6m 59s
- Adding functionality with extensions 3m 39s
- Using generics in Swift 8m 8s
- Conclusion 1m 2s
- Wrapping up 1m 2s
- Ex_Files_Swift_EssT.zip (0.03 MB)
This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.