Start learning free

LESSON 10 OF 349 · VARIABLES

Data Types in Swift in Swift

Lesson

TL ; DR:

In Swift, not all data is treated the same. There are different data types, such as:

  • Int - represents integer numbers like 3 and -12

  • Double - represents floating point numbers like 3.14

  • String - represents a string (sequence of characters) like "John Doe"

  • Bool - represents data that can have one of two values: true or false

  • Character - represents a single character like "a", "Z" or "?"



Full lesson:

One instruction can have several distinct meanings depending on the data types it's working with.

For example, suppose you see this line of code somewhere in a program:

print(a + b)

Can you tell for sure what it does without knowing anything about the variables a and b?

It might add two numbers, if a and b are both numbers:

var a = 10
var b = -5

print(a + b) // Output: 5

But it also might concatenate two strings, if a and b are both strings:

var a = "Hello "
var b = "world!"

print(a + b) // Output: Hello world!

Of course, addition and string concatenation are two completely different operations and Swift needs to figure out which one to do.

And this is exactly why Swift assesses the data type of every value you use in your program. In order to be able to make these decisions when needed.

In our example, when it reads a + b, Swift checks the data type of a and b. If both are strings, it performs string concatenation. If both are numbers, it performs addition.


Invalid operations:

Asessing data types is also helpful for Swift to make sure that what you do with the data actually makes sense.

For example, computers can perform mathematical operations on numbers, but not on strings. Of course, nobody can stop you from writing a program like this:

var a = "peanut"
var b = "butter"

print(a * b) // error: binary operator '*' cannot be applied to two 'String' operands

But when you try to run this program, Swift will throw a error: binary operator '*' cannot be applied to two 'String' operands.

This is the way of Swift telling you: "Hey, I'm a little confused. How do you multiply two strings? I've never heard of that."


Assignment
Follow the Coding Tutorial and let's practice with data types!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    Data Types in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free