</>
Skip to content
Swift lessons (7/33)

Swift — Data Types

Basic types

TypeDescription
Booltrue or false
Int64-bit signed integer
UInt64-bit unsigned integer
Float32-bit float
Double64-bit float
StringUTF-8 text
CharacterSingle Unicode character

Numeric types

let i: Int = 42
let d: Double = 3.14159
let f: Float = 3.14
let u: UInt = 42

print(i, d, f, u)

Strings

let s = "Hello, World!"
let multiline = """
    This is a
    multiline string
    """
let interpolated = "Length: \(s.count)"

Arrays

let nums = [1, 2, 3, 4, 5]
var mutable = [1, 2, 3]
mutable.append(4)
mutable.remove(at: 0)
print(mutable) // [2, 3, 4]

Dictionaries

let ages = ["Alice": 30, "Bob": 25]
print(ages["Alice"] ?? 0)

var mutable = [String: Int]()
mutable["Charlie"] = 35

Sets

let set: Set = [1, 2, 3, 2, 1]
print(set) // {1, 2, 3}
print(set.contains(2)) // true

Tuples

let point = (x: 3.0, y: 4.0)
print(point.x, point.y)

let (x, y) = point
print(x, y)

Structs

struct Point {
    var x: Double
    var y: Double

    func distance(to other: Point) -> Double {
        let dx = x - other.x
        let dy = y - other.y
        return sqrt(dx * dx + dy * dy)
    }
}

let p1 = Point(x: 0, y: 0)
let p2 = Point(x: 3, y: 4)
print(p1.distance(to: p2)) // 5.0

Enums

enum Direction {
    case north, south, east, west
}

enum HttpStatus: Int {
    case ok = 200
    case notFound = 404
    case serverError = 500
}

let dir = Direction.north
let code = HttpStatus.notFound
print(code.rawValue) // 404

Mini Practice

Write Swift code that:

  1. Creates arrays and dictionaries
  2. Defines a struct with a method
  3. Creates an enum with raw values
  4. Demonstrates tuple destructuring

Up Next

In the next lesson, you'll learn about Type Inference — Swift's type system.

Related Topics

Frequently Asked Questions about Data Types

What is Data Types in Swift?

Data Types is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Data Types?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Data Types.

Why is Data Types important in Swift?

Data Types is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.