Primitives in Swift

Find this useful? Support us: Star on GitHub 6
Category: Datatypes | Language: Swift

Sure!

In Swift, primitive types refer to the basic data types, or building blocks, used to construct more complex types. These types are considered "primitive" because they represent the most basic level of data storage and manipulation in the language.

Here are the most common primitive types in Swift with examples:

1. Integer types - Used to store whole numbers without a decimal point.

let myAge = 27 // Int
let numberOfStudents = 25 // Int
let number: UInt = 10 // Unsigned Integer

2. Floating-point types - Used to store numerical values with decimal points.
let pi = 3.14 // Double
let averageGrade = 89.5 // Double
let height: Float = 5.11 // Float

3. Boolean type - Used to store true/false values.
let isStudent = true
let isTeacher = false

4. Character type - Used to store single characters.
let firstInitial = "J"
let lastInitial: Character = "D" // Must specify Character

5. String type - Used to store text.
let greeting = "Hello, world!"
let fullName = "John Doe"

6. Optional types - Used to represent values that may be missing or nil.
var middleName: String? = nil
var numberOfPets: Int? = 2

I hope this helps! Let me know if you have any questions.