Swift Data Types (Int, Double, String) Example

1. Introduction

Swift provides a variety of data types to ensure clarity, precision, and efficiency in your programs. Among these, Int, Double, and String are some of the most commonly used. Int represents whole numbers, Double represents floating-point numbers, and String represents sequences of characters.

2. Source Code Example

// Declaring an integer variable
var age: Int = 25
print("My age is \(age) years.")

// Declaring a double variable
var averageScore: Double = 89.5
print("My average score is \(averageScore).")

// Declaring a string variable
var name: String = "John Doe"
print("My name is \(name).")

// Type inference in Swift
var inferredInt = 30
var inferredDouble = 15.5
var inferredString = "Hello, World!"
print("Inferred data types: \(inferredInt), \(inferredDouble), \(inferredString)")


My age is 25 years.
My average score is 89.5.
My name is John Doe.
Inferred data types: 30, 15.5, Hello, World!

3. Step By Step Explanation

1. An integer variable named age is declared of type Int and initialized with a value of 25. This represents a whole number without any decimal points. The value is then printed to the console.

2. A floating-point variable named averageScore of type Double is declared. It holds numbers that can have decimal values. In our example, the averageScore is 89.5.

3. A variable named name of the type String is declared. Strings in Swift can hold any sequence of characters. Here, it's initialized with the value "John Doe".

4. Swift also supports type inference, which means you don't always have to explicitly specify the data type. The Swift compiler can infer the type based on the value you provide. In the example, inferredInt, inferredDouble, and inferredString are variables where their types (Int, Double, and String respectively) are inferred by the compiler based on the values assigned.