Lesson 3Swift Basics
Data Types
Swift Data Types
Every variable in Swift has a specific type that determines what kind of data it can hold. Swift is a type-safe language!
Common Data Types
Int
Whole numbers: 1, 42, -100
Double
Decimals: 3.14, -0.5, 99.99
String
Text: "Hello", "Swift"
Bool
True or False values
Type Inference
Swift is smart! It can figure out the type automatically based on the value you assign:
42→ Int3.14→ Double"Hi"→ Stringtrue→ Bool
Type Annotations
You can explicitly specify the type using a colon:
let age: Int = 12main.swift
// Integer - whole numbers
let age: Int = 12
var score: Int = 100
let negative: Int = -50
// Double - decimal numbers (more precision)
let pi: Double = 3.14159265359
let price: Double = 9.99
// Float - decimal numbers (less precision)
let temperature: Float = 98.6
// String - text
let name: String = "Swift"
let message: String = "Hello, World!"
// Bool - true or false
let isStudent: Bool = true
let gameOver: Bool = false
// Type inference - Swift figures it out!
let inferredInt = 42 // Int
let inferredDouble = 3.14 // Double
let inferredString = "Hi" // String
let inferredBool = true // Bool
// Check the type
print(type(of: inferredInt)) // Int
print(type(of: inferredDouble)) // DoubleTry It Yourself!
Create variables for: your age (Int), height in meters (Double), your name (String), and whether you like coding (Bool)!