Let's write some code!
To start playing with Swift, you need to open up a Playground on your Mac. You should already know how to do that – you learned it in the Playground tutorial.
Once you're ready, follow the instructions below.
When you open up a fresh playground you can see couple of lines already there. There will be a statement on the top that says
UIKit is the framework that you'll find yourself use most often when developing iOS applications. It defines the core components of an iOS application, from labels and buttons and table views and much more. We will be covering all of this in the later tutorials for creating our app.
For now, even if that statement is removed it won't affect the playground as we are going to be covering the fundamentals in the upcoming tutorials.
The grey area on the right side is the result bar where the result of each line of code is printed.
Go ahead and try to add two numbers, lets say 5 and 3. You should be able to see the number 8 being printed on the right side.
Nice! See how the answer popped out? Swift knows math!
Instead of including a screenshot each time, in the future we'll include the code's output as a comment on the next line. In Swift, we can write a comment by using //.
For example, we will write:
5 + 3// 8 (output)
You could try other commands like:
- 4 * 5
- 5 - 1
- 40 / 2
When you play around with division, you might notice something interesting. When you divide, the result is always an integer. For example:
14 / 5// 2 (output)
The result is 2 instead of 2.8. This is because an integer (example, 2, 10, -7) is a different data-type in Swift than a decimal (example, 2.8, 3.14, -5.1). When you divide two integers, Swift returns an integer as the result.
If instead you want to calculate and want decimal values in the answer, then you have to use decimal values in the expression you provide to Swift.
14.0 / 5.0// 2.87.2 / 2.5// 2.887.0 / 3// 2.3333333333
Notice that you don't necessarily have to use the decimal values for both the values. If you use decimal value for any one of them, that works.
You can also convert an integer to float before using it. For example:
Float(14) / 5// 2.8
This is called type-conversion, and we'll describe this is much more detail at the end of this tutorial.
Have fun with this for a little while and then get back here. :)
There is another operator called the modulus operator. This operator tells you the remainder that is left when you divide a number by another number. For example,
14 % 5// 4 (output)
We get 4 because when 14 is divided by 5, the remainder is 4.
For reference, at the end of the article, we have included a table with a list of all arithmetic operators in Swift.
Each of the lines above that you typed into the Swift is called an expression. Expressions can be much longer too. For example, try this:
(5 + 2) * (7 - 1) / 3// 14
In Swift (and other programming languages as well), all expressions evaluate to a single value. You saw this above for some simple expressions such as 5 + 3 which evaluates to 8.
Here's a step-by-step breakdown of how the above expression is evaluated in Swift.
(5 + 2) * (7 - 1) / 3=> (7) * (7 - 1) / 3=> 7 * (7 - 1) / 3=> 7 * (6) / 3=> 7 * 6 / 3=> 42 / 3=> 14
Swift does the above behind the scenes, and tells us what the final result of evaluating the expression is.
As you can see, Swift is a great calculator. If you're wondering what else you can do…
How about your name? Type your first name in quotes like this:
"Commonlounge"// "Commonlounge" (output on the right hand side)
You've now created your first string! It's a sequence of characters that can be processed by a computer. The string must always begin and end with double quotes (") . The quotes tell Swift that what's inside of them is a string.
Strings can be strung together. Try this:
"Hi there " + "Commonlounge"// "Hi there Commonlounge"
Notice how we had to end the first string ("Hi there ") with a space (" "). If we did not, then our result would be "Hi thereCommonlounge", which isn't what we want.
If you need to put double quotes inside your string, you can do it by escaping the double quotes with a backslash (\):
"Julius said \"Et tu, Brute?\" before dying"// "Julius said "Et tu, Brute?" before dying"
Nice, huh? To see your name in uppercase letters, simply type:
You just used the uppercased method on your string! A method (like uppercased()) is a sequence of instructions that Swift has to perform on a given object ("Commonlounge") once you call it.
lowercased is another method that we can apply to our strings. It is used to convert entire content to lowercase.
If you want to know the number of letters contained in your name, do the following:
Wonder why we used brackets for .uppercased() but not for .count? That's because uppercased is a method whereas count is a variable attribute. When we use a method, Swift needs to do some calculations to calculate the result we asked for. When we use an attribute, the result is already stored somewhere.
Xcode also highlights for you the difference between these two:
The symbol M stands for Method
The symbol V stands for Variable attribute.
We'll be learning more about Swift Strings and Swift functions later in the course.
Let's try something new. Can we add a number and a string?
We got our first error! Making mistakes (even intentional ones) are an important part of learning! In particular, an error doesn't mean something bad is going to happen with the computer. It's just Swift's way of saying, “Something's wrong.” or “I don't understand.”
It says that objects of type "Int" (integers, whole numbers) and "String" cannot be added by "+".
You'll get a similar error if you try to find the length of an integer. For example, try doing,
304023.count// Gives an error!
To fix this, we need to first convert our Int to a String, and then use the .count attribute on that.
It worked! We used the String function to convert our number to a string and used the attribute .count to tell us number of characters.
Note: Make sure the 'S' is capital or it won't work
You can use the String() function to convert anything to a string.
Converting things to an integer is slightly trickier. If you do Int("52"), you'll get something called an Optional. It's an Optional because we can convert numbers into text, but we can't necessarily convert text into numbers – what would Int("hello") be anyway?
However, we do know that we are going to do Int("52"). So, you can unwrap an optional using !. Swift uses exclamation marks to force unwrapping of optionals. You are basically telling Swift "I know this optional variable definitely has a value, so let me use it."
Here's an example:
Int("52")// Optional(52)Int("52")!// 52
Once we have unwrapped the Optional, we can use it for further calculations. For example:
Int("52") + 1// Error!Int("52")! + 1// 53
- The String() function converts things into strings
- The Int() function converts things into integers, but you need to use ! to unwrap the Optional.
- The Float() function (which you saw earlier), works the same way as the Int() function.
Note: You only need to unwrap if converting from String to Int / Float. Not if you convert from Int to Float or from Float to Int.
OK, enough of strings. So far you've learned about:
- numbers and strings – in Swift numbers are used for math and strings for text objects
- operators – like + and *, combine values to produce a new one
- methods – like uppercased() and lowercased(), perform actions on objects.
- errors – you now know how to read and understand errors that show up if Swift doesn't understand a command you've given it
- type conversion - how to convert something to a String, Int or Float
These are the basics of every programming language you learn. Ready for something harder? We bet you are!
The following is a list of all arithmetic operations supported by Swift.
Operator | Example | Result | Description---------|-----———--|--------|------------------------------------------------+ | 4 + 5 | 9 | addition- | 4 - 5 | -1 | subtraction* | 4 * 5 | 20 | multiplication/ | 8 / 3 | 2.666 | division% | 14 % 3 | 2 | modulo (remainder left after division)