Swift Basics

Data types

Data is a piece of information, it’s the basic unit in programming the we use to build programs. Without it, we couldn’t write any programs.

Data types (or just types) are different types of data that indicates characteristics of data so the computer can perform the appropriate operation.

In short, they tell us how data can be stored and what types of operations we can perform. For example, we can write a program that squares numbers, but it wouldn’t be able to square a word.

The most basic data types are called primitives. They are so basic that you can find them in pretty much every programming language. They include:

  • Numbers
  • Strings
  • Boolean values (True or False)

Every variable in Swift must be of a specific data type. That’s because Swift is a type-safe language. You set the type when you declare a variable and you must keep the same type if you change the value of that variable later.

Type inferring

So far, we didn’t specify the data type for our variables because we relied on the type inferring feature of Swift. This means that Swift can recognize automaticaly the data type of the most common values and set the corrent data type for us when we declare the variable.

Remember how we declared str = "Have a nice day" ?

The value "Have a nice day" we assigned to the str variable is of type String and it’s very easy for Swift to recognize it, because it’s enclosed in double quotes.

Without type inferring, we would have to specify the data type like this:

str: String = "Have a nice day"

Go ahead and write this code to the bottom of your playground (delete the line where you attempted to change the value of the birthdate constant first):

var name: String = "Jan"

This is how your code should look like now:

enter image description here

Similarly, you could specify the type of Integer for your age variable like this:

var age: Int = 40

Int stands for Integer and it means a simple number. Go ahead and modify your code so it includes the specification of Integer type:

enter image description here

« Previous: Constants Next: Strings and integers »