Notice: Undefined index: understanding-swift in /var/sites/ on line 89
Why is Swift a type-safe language? - a free tutorial

NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Why is Swift a type-safe language?

Paul Hudson    @twostraws   

Swift lets us create variables as strings and integers, but also many other types of data too. When you create a variable Swift can figure out what type the variable is based on what kind of data you assign to it, and from then on that variable will always have that one specific type.

For example, this creates a new variable called meaningOfLife equal to 42:

var meaningOfLife = 42

Because we assigned 42 as the initial value of meaningOfLife, Swift will assign it the type integer – a whole number. It’s a variable, which means we can change its value as often as we need to, but we can’t change its type: it will always be an integer.

This is extremely helpful when building apps, because it means Swift will make sure we don’t make mistakes with our data. For example, we can’t write this:

meaningOfLife = "Forty two"

That tries to assign a string to a variable that is an integer, which isn’t allowed. Although we rarely make such an obvious mistake, you will find that this type safety helps out every single day you’re writing code with Swift.

Think about it: we just created one variable then tried to change its type, which will obviously fail. But as your programs grow in size and complexity, it becomes impossible to keep the types of your variables in your head at all times, so we’re effectively shifting that work on to Swift instead.

Hacking with Swift is sponsored by Instabug

SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.

Start your free trial!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Link copied to your pasteboard.