Variables, Constants, and Data Types in Swift
# CHAPTER 4
Variables, Constants, and Data Types in Swift
1. Introduction
In the previous chapter, we quickly touched onvar 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
letandvar.
- Understand Swift's powerful "Type Inference" engine.
-
Explicitly annotate data types (
Int,Double,Float,String,Bool).
-
Understand the difference between
DoubleandFloat.
- 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 writevar 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.
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.
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): Strictlytrueorfalse.
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!
8. Type Conversion (Casting)
Because Swift is Type-Safe, you cannot do math with anInt and a Double directly. Swift won't let you mix apples and oranges. You must explicitly convert one of them!
Converting Strings to Integers (e.g., getting a phone number from a text box):
9. Common Mistakes
-
Type Changing: JavaScript allows
let data = 10; data = "Hello";. Swift does NOT. Once a variable is inferred as anInt, it is anIntfor 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 aDoubleby default. If you try to pass that to a function that explicitly requires aFloat, it will fail. Always rely onDoublein iOS unless forced otherwise.
10. Best Practices
-
Let the Compiler Infer: You do not need to write
var name: String = "Alice". Writingvar 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.
Explicitly declare a variable named
temperatureof typeDoubleand assign it72.5.
-
2.
Use String Interpolation to print a sentence containing the
temperaturevariable.
12. Coding Challenges
Challenge: Create a constantInt 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
What is the definition of Swift's "Type Inference" engine?
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
DoubleandFloatdata types. Why does Swift's type inference engine default toDoublewhen processing a decimal literal?
-
Q: A developer attempts to add a
Stringrepresenting a number ("5") to anInt(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 oflet 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.