Swift is strongly typed to help catch mistakes early and make your code safer and easier to understand.
0
0
Why Swift is strongly typed
Introduction
When you want to avoid mixing up different kinds of data by mistake.
When you want the computer to help find errors before running your program.
When you want your code to be clear about what kind of data each part uses.
When you want to write code that is easier to maintain and less likely to crash.
When you want to use features like autocomplete and better error messages in your editor.
Syntax
Swift
var name: String = "Alice" let age: Int = 30 // The type (String, Int) is declared explicitly
Swift requires you to specify or infer the type of each variable or constant.
This helps the computer understand what kind of data it is working with.
Examples
Here,
message is a string and number is an integer.Swift
var message: String = "Hello" let number: Int = 10
You can let Swift guess the type if you assign a value right away.
Swift
var count = 5 // Swift infers that count is an Int
You can declare the type first, then assign a value later.
Swift
var price: Double price = 9.99
Sample Program
This program shows how Swift expects the right type for each variable. If you try to assign a string to an integer variable, Swift will stop you with an error.
Swift
var name: String = "Bob" var age: Int = 25 // Trying to assign a wrong type causes an error // age = "twenty-five" // This line would cause a compile error print("Name: \(name)") print("Age: \(age)")
OutputSuccess
Important Notes
Strong typing helps prevent bugs by making sure data types match.
Swift's type system also improves code readability and tooling support.
Sometimes you need to convert between types explicitly to avoid errors.
Summary
Swift is strongly typed to catch errors early and keep code safe.
Every variable and constant has a clear data type.
This makes your code easier to read and less error-prone.