Safety is one of the core features of Swift. Apple has incorporated many safe programming patterns into the language to save you from making some common programmer mistakes. A safer type system is one of the ways that Swift helps you write code that’s safer and less error-prone.
Let’s look at a few features…
A Type Safe or strongly typed language tries to protect you from making mistakes with types. For example, you cannot assign an integer to a variable that was previously declared as a string.
Here’s how Apple describes type safety in Swift:
Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This restriction enables you to catch and fix errors as early as possible in the development process.
Let’s take a look at an example. Open Terminal and boot up the REPL:
We will first declare a String variable, and then try to assign an Integer to our variable:
Looks like we got an error:
As you can see, Swift is a strongly typed language, and that error message - which hopefully will be more descriptive and meaningful as the tooling evolves - is its way of telling you that you cannot assign an integer to a String.
Languages check for type errors either when you present the code to the compiler or interpreter (compile-time checking), or when the code is being executed (run-time checking). Let’s examine when Swift checks for type errors.
Enter the following code into the REPL:
1 2 3 4 5
The moment the code is complied, an error is reported:
As you can see, Swift type checks the code at compile-time and gives you an error even before you call the
Many modern programming languages, check for type errors at compile time, since it helps catching the errors earlier. These language are sometimes referred to as statically typed languages.
Dynamically typed languages, such as Ruby, on the other hand, check for type errors when you actually try to execute code (at run-time).
Swift helps you avoid type errors by type checking your code at compile time. But that doesn’t mean that you have to explicitly write the type of every variable and constant you declare.
Type Inference is another nifty feature of Swift that allows it to work out the type of the expressions you provide by examining the values.
Let’s look at an example: Without type inference you declare a Double like this:
: Double part tells the compiler that you are declaring a variable of type Double.
Thanks to type inference, however, you can get rid of the annotation part and declare your variable like this:
Swift is capable of deducing the type of myDouble by examining its value of 1.0, and frees you from having to type it out explicitly.