Skip to main content
Swift for iOS Development
CHAPTER 04 Beginner

Variables, Constants, and Data Types in Swift

Updated: May 16, 2026
6 min read

# CHAPTER 4

Variables, Constants, and Data Types in Swift

1. Introduction

In the previous chapter, we quickly touched on var and let. In professional iOS development, understanding exactly how data is structured in memory is what separates amateurs from seniors. Swift is a "Type-Safe" language. This means if you create a box designed to hold an Integer (whole number), and you try to shove a piece of Text into it, Xcode will violently refuse to compile your app. In this chapter, we will master Variables, Constants, and Data Types. We will explore explicit type annotations, type inference, and how to safely convert data from one format to another.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Clearly define the architectural difference between let and var.
  • Understand Swift's powerful "Type Inference" engine.
  • Explicitly annotate data types (Int, Double, Float, String, Bool).
  • Understand the difference between Double and Float.
  • Perform Type Conversion (Casting) to mix different data types safely.
  • Use String Interpolation to inject variables into text.

3. let vs var (Immutability)

As discussed:
  • var (Variable): Mutable data. It can be changed.
  • let (Constant): Immutable data. Once assigned, it is locked in memory forever.

Why use let? If you define let maxPlayers = 4, and a junior developer tries to write code later that accidentally sets maxPlayers = 5, the compiler will block them. It prevents human error and optimizes memory!

4. Type Inference (Swift is Smart)

When you write var score = 10, you didn't tell Swift it was a number. Swift uses Type Inference. It looks at the 10, realizes it is a whole number, and automatically locks the score variable to *only* accept whole numbers forever.
swift
123
var username = "Alice" // Swift infers this is a String
username = "Bob"       // Allowed! It's still a String.
// username = 42       // ERROR! You cannot put an Integer into a String variable.

5. Explicit Data Types

Sometimes, you want to be explicit, or you want to create an empty variable to fill later. You do this using a colon : to define the Type.
swift
123456
// Syntax: var name: Type = Value

var age: Int = 25
var pi: Double = 3.14159
var message: String = "Hello"
var isLoggedIn: Bool = true

6. The Core Data Types Explained

  • Int (Integer): Whole numbers only. Positives and negatives. (10, -5, 0).
  • Double: High-precision decimal numbers. (3.14159265...). This is the default in Swift!
  • Float: Low-precision decimal numbers. Takes up less memory, but less accurate. Rarely used today unless a specific game engine requires it.
  • String: Text. Surrounded by " ".
  • Bool (Boolean): Strictly true or false.

7. String Interpolation (Injecting Variables)

If you want to print "Hello, Alice! You are 25 years old", you don't want to use clunky plus signs. Swift uses String Interpolation. You use a backslash and parentheses \() to inject *any* variable directly into a string!
swift
12345
let playerName = "Zelda"
let level = 50

// Injecting variables directly into the text!
print("Welcome back, \(playerName)! You are currently on Level \(level).")

8. Type Conversion (Casting)

Because Swift is Type-Safe, you cannot do math with an Int and a Double directly. Swift won't let you mix apples and oranges. You must explicitly convert one of them!
swift
12345678
let wholeNumber: Int = 10
let decimalNumber: Double = 4.5

// let result = wholeNumber + decimalNumber // ERROR! Int + Double not allowed!

// Solution: Convert the Int into a Double for the math calculation!
let result = Double(wholeNumber) + decimalNumber
print(result) // Prints 14.5

Converting Strings to Integers (e.g., getting a phone number from a text box):

swift
123
let stringAge = "25"
// Convert String to Int!
let realAge = Int(stringAge) 

9. Common Mistakes

  • Type Changing: JavaScript allows let data = 10; data = "Hello";. Swift does NOT. Once a variable is inferred as an Int, it is an Int for the rest of its life. Trying to assign a String to it later will crash the compiler.
  • Float vs Double: If you write var math = 3.14, Swift infers it as a Double by default. If you try to pass that to a function that explicitly requires a Float, it will fail. Always rely on Double in iOS unless forced otherwise.

10. Best Practices

  • Let the Compiler Infer: You do not need to write var name: String = "Alice". Writing var name = "Alice" is cleaner and is the standard practice among Apple engineers. Only use explicit types (: String) when the variable starts off empty.

11. Exercises

  1. 1. Explicitly declare a variable named temperature of type Double and assign it 72.5.
  1. 2. Use String Interpolation to print a sentence containing the temperature variable.

12. Coding Challenges

Challenge: Create a constant Int named score equal to 100. Create a constant Double named multiplier equal to 1.5. Multiply them together and store the result in a new constant. (Hint: You must use Type Conversion!).

13. MCQ Quiz with Answers

Question 1

What is the definition of Swift's "Type Inference" engine?

Question 2

Which syntax is correctly used to perform String Interpolation (injecting a variable directly into a string literal) in Swift?

14. Interview Questions

  • Q: Explain the concept of "Type Safety" in Swift. Provide an example of an operation that JavaScript would allow, but Swift's type-safety architecture would explicitly reject during compilation.
  • Q: Contrast the Double and Float data types. Why does Swift's type inference engine default to Double when processing a decimal literal?
  • Q: A developer attempts to add a String representing a number ("5") to an Int (10). Explain the explicit Type Conversion steps required to successfully execute this mathematical operation.

15. FAQs

Q: Can I put emojis in my Strings? A: Yes! Swift fully supports Unicode. You can even name your variables with emojis (e.g., let 🍎 = "Apple"), though your senior developer might be very angry with you if you do!

16. Summary

In Chapter 4, we dove deep into memory management and Type Safety. We reinforced the architectural dominance of let over var to enforce immutability. We allowed Swift's Type Inference engine to write cleaner code, while mastering explicit annotations for core types like Int, Double, String, and Bool. Finally, we successfully combined different data types using explicit Type Conversion and injected live memory data into text using elegant String Interpolation.

17. Next Chapter Recommendation

We know how to store data. Now we need to make decisions with it. How do we check if a score is greater than 100? How do we loop through a list? Proceed to Chapter 5: Operators, Conditions, and Loops.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·