# Swift Data Types Explained: Int, Double, String, Bool and Their Limits

Source: https://devdocs10.com/articles/swift/swift-data-types  
By Murat Bo · Updated 2026-10-28 · DevDocs10 (https://devdocs10.com)

Swift's core data types are `Int` for whole numbers, `Double` for decimal numbers, `String` for text, `Character` for one visible character, and `Bool` for true or false. Each has hard limits that the compiler or the running program enforces: an `Int` on a 64-bit device stops at 9,223,372,036,854,775,807 and crashes the program if a calculation goes past it, a `Double` cannot store 0.1 exactly, a `String` cannot be indexed with an integer, and a `Bool` is never a number. This page shows what each type is for, demonstrates those limits with real output, and ends with a table for choosing the right type.

> **Difficulty:** Beginner
>
> **Helpful to know first:** How to declare values with `let` and `var`, and how `print()` shows a value.

## How Swift Types Work: One Type per Value, No Silent Conversion

Every value in Swift has exactly one type, fixed when the code is compiled. The type decides which values are allowed, how much memory they use and which operations work on them. Swift never converts between types on its own, not even between two kinds of numbers.

```swift
let quantity = 3          // Int
let unitPrice = 4.99      // Double
let product = "Notebook"  // String
let inStock = true        // Bool

let total = Double(quantity) * unitPrice
print(product, quantity, total, inStock)
// Output: Notebook 3 14.97 true
```

Output (tested with Swift 6.4):

```text
Notebook 3 14.97 true
```

Swift inferred all four types from the literals. The multiplication needs `Double(quantity)`: without it, `quantity * unitPrice` fails with `binary operator '*' cannot be applied to operands of type 'Int' and 'Double'`. That strictness is deliberate. JavaScript, for example, quietly turns `"3" * 2` into `6`; in Swift every conversion is visible in the code, so the reader can see where precision might be lost.

This page is about what the types can hold. To write a type yourself with `: Int` or `: Double`, see [Swift type annotation](/articles/swift/swift-type-annotation); for how Swift picks a type when you do not write one, see [Swift type inference](/articles/swift/swift-type-inference).

## What Each Core Type Is For, and Where It Stops

### Int: whole numbers in a fixed range

Use `Int` for counts, indexes, scores and anything else without a fractional part. Its size matches the platform: 64 bits on Macs, iPhones, iPads and 64-bit Linux, and 32 bits on 32-bit targets such as the arm64_32 architecture used by many Apple Watch models. Fixed-size types (`Int8`, `Int32`, `UInt8` and so on) exist for file formats and C APIs.

```swift
print(Int.max)
print(Int.min)
print(MemoryLayout<Int>.size)
print(Int8.max, UInt8.max, Int32.max)
// Output:
// 9223372036854775807
// -9223372036854775808
// 8
// 127 255 2147483647
```

Output (tested with Swift 6.4):

```text
9223372036854775807
-9223372036854775808
8
127 255 2147483647
```

The third line shows that an `Int` takes 8 bytes on this 64-bit Mac. Prefer `Int` even for values that can never be negative: Swift's own APIs (`count`, indexes) use `Int`, and mixing in `UInt` forces conversions everywhere.

### Double and Float: fast decimal numbers that are not exact

Use `Double` for measurements, coordinates, percentages and scientific values. A decimal literal such as `3.14` is a `Double` unless you ask for something else. `Double` stores numbers in binary with about 15 to 17 significant decimal digits; `Float` uses half the memory and keeps only about 6 to 9.

```swift
let a = 0.1
let b = 0.2
print(a + b)
print(a + b == 0.3)
print(abs((a + b) - 0.3) < 1e-9)
// Output:
// 0.30000000000000004
// false
// true
```

Output (tested with Swift 6.4):

```text
0.30000000000000004
false
true
```

0.1 and 0.2 have no exact binary form, just as 1/3 has no exact decimal form, so their sum is a tiny bit more than 0.3. Compare floating-point results with a tolerance, as on the third line, never with `==`. Precision also runs out for large whole numbers:

```swift
let f: Float = 16_777_217
let d: Double = 16_777_217
print(f, d)
// Output: 16777216.0 16777217.0
```

Output (tested with Swift 6.4):

```text
16777216.0 16777217.0
```

A `Float` cannot represent 16,777,217, so it silently becomes 16,777,216. The compiler warns here (`'16777217' is not exactly representable as 'Float'; it becomes '16777216'`), but only because the value is a literal; results of calculations get no warning. A `Double` hits the same wall above 9,007,199,254,740,992 (2 to the power of 53). Choose `Float` only when an API asks for it, such as graphics or machine-learning code.

### String and Character: text counted in visible characters

Use `String` for any text. A `Character` is one extended grapheme cluster, which is what a person sees as one character, even when it is made of several Unicode scalars. Swift counts and compares text in those visible characters.

```swift
let word = "café"
let family = "👨‍👩‍👧"

print(word.count, word.utf8.count)
print(family.count, family.unicodeScalars.count)

let accent: Character = "é"
print(word.last == accent)
print("e\u{301}" == "é")
// Output:
// 4 5
// 1 5
// true
// true
```

Output (tested with Swift 6.4):

```text
4 5
1 5
true
true
```

`"café"` is 4 characters but 5 bytes in UTF-8, because `é` needs two bytes. The family emoji is five Unicode scalars (three people joined by two invisible joiners) but one `Character`. The last line shows that a plain `e` followed by a combining accent equals the single precomposed `é`: Swift compares text by meaning, not by bytes.

The price of this correctness is that a `String` cannot jump to "character number 3" without walking from the start, so Swift offers no integer subscript, and `count` has to walk the whole string. A `Character` literal needs a type annotation, because `"é"` alone is a `String`. [Unicode and grapheme clusters](/articles/swift/swift-unicode-graphemes) goes deeper.

### Bool: true or false, never a number

Use `Bool` for yes-or-no state. Comparisons produce a `Bool`, and `if`, `while` and `guard` accept only a `Bool`: there is no "truthy" 1 or empty string as in C, JavaScript or Python.

```swift
var isMuted = false
isMuted.toggle()

let unreadCount = 3
let hasUnread = unreadCount > 0
print(isMuted, hasUnread, !hasUnread)

print(Bool("true") ?? false, Bool("yes") ?? false, Bool("TRUE") ?? false)
// Output:
// true true false
// true false false
```

Output (tested with Swift 6.4):

```text
true true false
true false false
```

`toggle()` flips a `var` in place. Converting text to `Bool` accepts only the exact words `"true"` and `"false"`, so `"yes"` and even `"TRUE"` give `nil`, replaced here by `false`.

### Converting between types on purpose

Every conversion is an initializer call, and each one has a rule you need to know. Number-to-number conversions always produce a value; text-to-number conversions return an optional, because the text might not be a number.

```swift
print(Int(3.99), Int(-3.99), Int(3.99.rounded()))
print(Int("42") ?? 0, Int("4.2") ?? 0, Int(" 42") ?? 0)
print(Double("3.14") ?? 0, String(7) + "%")
// Output:
// 3 -3 4
// 42 0 0
// 3.14 7%
```

Output (tested with Swift 6.4):

```text
3 -3 4
42 0 0
3.14 7%
```

`Int(3.99)` cuts off the fraction instead of rounding; call `rounded()` first if you want 4. `Int("4.2")` and `Int(" 42")` are both `nil`: the text must be a whole number with no spaces. Optionals are covered in [Swift optionals](/articles/swift/swift-what-are-optionals).

## How Swift Number Types Behave at the Edges

### Integer division and remainder round toward zero

Dividing two `Int` values gives an `Int`, and the fraction is dropped, toward zero for negative numbers too. The remainder takes the sign of the left-hand number.

```swift
print(7 / 2, -7 / 2)
print(7 % 2, -7 % 2)
print(7.0 / 2)
// Output:
// 3 -3
// 1 -1
// 3.5
```

Output (tested with Swift 6.4):

```text
3 -3
1 -1
3.5
```

That is why `-7 % 2 == 1` is false in Swift. Test for an odd number with `n % 2 != 0` or `!n.isMultiple(of: 2)` instead.

### Integer overflow stops the program

Swift checks every `+`, `-` and `*` on integers. If the compiler can see the overflow, the build fails: `let big = Int.max + 1` gives `arithmetic operation '9223372036854775807 + 1' (on type 'Int') results in an overflow`, and `let level: Int8 = 128` gives `integer literal '128' overflows when stored into 'Int8'`. If the overflow only happens at run time, the program stops immediately:

```swift
func addBonus(to score: Int) -> Int {
    score + 1
}

print(addBonus(to: Int.max))   // stops the program: arithmetic overflow
```

In Terminal the program ends with a trap signal and Swift prints no message of its own (the shell may report a "trace trap"); in Xcode the debugger stops on the line with `Swift runtime failure: arithmetic overflow`. Unlike C, Swift keeps this check in optimized release builds. When wrapping around is what you want, for hashes or checksums, say so with the overflow operators:

```swift
let big = Int.max
print(big &+ 1)

let (value, didOverflow) = big.addingReportingOverflow(1)
print(value, didOverflow)
// Output:
// -9223372036854775808
// -9223372036854775808 true
```

Output (tested with Swift 6.4):

```text
-9223372036854775808
-9223372036854775808 true
```

`&+` wraps silently; `addingReportingOverflow` wraps and tells you it happened. See [Swift overflow operators](/articles/swift/swift-overflow-operators) for the whole family.

### Division by zero: a crash for Int, infinity for Double

The two number families fail differently. `Int` division by zero at run time stops the program with `Fatal error: Division by zero` (a literal `10 / 0` does not even compile). `Double` follows the IEEE 754 standard and keeps going with special values:

```swift
print(1.0 / 0.0, -1.0 / 0.0)

let notANumber = 0.0 / 0.0
print(notANumber, notANumber == notANumber, notANumber.isNaN)
// Output:
// inf -inf
// nan false true
```

Output (tested with Swift 6.4):

```text
inf -inf
nan false true
```

NaN ("not a number") is not equal even to itself, so always test it with `isNaN`. Converting it, or infinity, to an `Int` crashes with `Fatal error: Double value cannot be converted to Int because it is either infinite or NaN`.

### How much memory each type takes

On a 64-bit platform, `MemoryLayout<T>.size` reports 8 bytes for `Int` and `Double`, 4 for `Float`, 1 for `Bool`, and 16 for both `String` and `Character`. A `String` stores up to 15 UTF-8 bytes inside those 16 bytes and puts longer text in a separate buffer, so short strings need no extra allocation. [MemoryLayout and alignment](/articles/swift/swift-memorylayout-alignment) explains size, stride and padding.

## Predict the Output

### Comparing a sum with 0.3

What does this print?

```swift
let total = 0.1 + 0.2
if total == 0.3 {
    print("equal")
} else {
    print("not equal: \(total)")
}
```

Output (tested with Swift 6.4):

```text
not equal: 0.30000000000000004
```

**Answer:**

It prints `not equal: 0.30000000000000004`. The binary approximations of 0.1 and 0.2 add up to slightly more than the approximation of 0.3, and `==` compares the exact bits. The compiler even works this out ahead of time and warns `will never be executed` on the `"equal"` branch.

### Counting characters and bytes

What does this print?

```swift
let word = "naïve"
let flag = "🇯🇵"
print(word.count, word.utf8.count)
print(flag.count, flag.unicodeScalars.count)
```

Output (tested with Swift 6.4):

```text
5 6
1 2
```

**Answer:**

It prints `5 6` and then `1 2`. `"naïve"` has five visible characters, but `ï` takes two bytes in UTF-8. A flag emoji is built from two regional-indicator scalars that together form one `Character`. Use `count` for what users see and `utf8.count` for storage or network limits.

## Type Mistakes That Break Swift Code

### Multiplying an Int by a Double

Quantities are usually `Int` and prices `Double`, so the first calculation that mixes them fails.

**Problem:** Swift has no implicit numeric conversion, so this stops with `error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'`.

```swift
let items = 3
let price = 4.5
let total = items * price
```

**Fix:** Convert the `Int` explicitly, so both operands are `Double`.

```swift
let items = 3
let price = 4.5
let total = Double(items) * price
print(total)
// Output: 13.5
```

Output (tested with Swift 6.4):

```text
13.5
```

This works because both sides of `*` now have the same type.

### Reading a character with an integer index

In most languages `text[0]` gives the first character, so people try it in Swift.

**Problem:** Swift strings have no integer subscript, because finding character number *n* means walking the string. The compiler says `error: 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.`

```swift
let name = "Swift"
print(name[0])
```

**Fix:** Use `first`, `prefix`, or a `String.Index` made with `index(_:offsetBy:)`.

```swift
let name = "Swift"
let third = name[name.index(name.startIndex, offsetBy: 2)]
print(name.first ?? "?", third, name.prefix(3))
// Output: S i Swi
```

Output (tested with Swift 6.4):

```text
S i Swi
```

These work because they walk the string by visible characters, which is what the index represents.

### Using a number as a condition

Code ported from C, JavaScript or Python often tests a count directly.

**Problem:** An `if` condition must be a `Bool`, so this fails with `error: type 'Int' cannot be used as a boolean; test for '!= 0' instead`.

```swift
let unreadCount = 3
if unreadCount {
    print("You have mail")
}
```

**Fix:** Write the comparison you mean.

```swift
let unreadCount = 3
if unreadCount > 0 {
    print("You have mail")
}
// Output: You have mail
```

Output (tested with Swift 6.4):

```text
You have mail
```

This works because `unreadCount > 0` produces a real `Bool`.

### Storing money in a Double

This one compiles and runs, which makes it worse: the answer is just slightly wrong.

**Problem:** Adding ten payments of 0.10 in a `Double` does not give exactly 1.0, so a check against the expected total fails and the printed amount looks broken.

```swift
var balance = 0.0
for _ in 1...10 {
    balance += 0.1
}
print(balance, balance == 1.0)
// Output: 0.9999999999999999 false
```

Output (tested with Swift 6.4):

```text
0.9999999999999999 false
```

**Fix:** Count money in the smallest unit as an `Int` (cents), or use Foundation's `Decimal` type.

```swift
var balanceInCents = 0
for _ in 1...10 {
    balanceInCents += 10
}
print(balanceInCents, balanceInCents == 100)
// Output: 100 true
```

Output (tested with Swift 6.4):

```text
100 true
```

Integer cents are exact, so totals and comparisons always match what a person would calculate by hand.

## Find the Bug

This code should print the average score, 82.33… Why does it print `Average: 82.0`?

```swift
let scores = [90, 85, 72]
let average = Double(scores.reduce(0, +) / scores.count)
print("Average: \(average)")
```

Output (tested with Swift 6.4):

```text
Average: 82.0
```

**Answer:**

The conversion happens too late. `scores.reduce(0, +) / scores.count` is `247 / 3`, an `Int` division that gives `82`. Only then does `Double(...)` turn 82 into 82.0; the fraction was already gone. Convert both operands before dividing:

```swift
let scores = [90, 85, 72]
let average = Double(scores.reduce(0, +)) / Double(scores.count)
print("Average: \(average)")
// Output: Average: 82.33333333333333
```

Output (tested with Swift 6.4):

```text
Average: 82.33333333333333
```

## Choosing the Right Type for a Value

| Type | Use it for | Range or precision | Watch out for |
| --- | --- | --- | --- |
| `Int` | Counts, indexes, IDs you do arithmetic on | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (64-bit) | Overflow stops the program; `/` drops the fraction |
| `Double` | Measurements, coordinates, ratios | About 15–17 significant digits | 0.1 + 0.2 != 0.3; never compare with `==` |
| `Float` | APIs that require it (graphics, ML) | About 6–9 significant digits | Loses whole numbers above 16,777,216 |
| `String` | Any text | Limited only by memory | No integer subscripts; `count` walks the text |
| `Character` | One visible character | One grapheme cluster, possibly several scalars | Needs `: Character`; `"AB"` is not one |
| `Bool` | Yes-or-no state | `true` or `false` | No numbers or strings as conditions |

A few choices are less obvious. Money belongs in an `Int` of cents or a `Decimal`, not a `Double`. Phone numbers, postal codes and card numbers belong in a `String`, because you never do arithmetic on them and `Int("007")` becomes `7`, losing the leading zeros. And when a value has more than two states, such as loading, loaded and failed, an enum is clearer than several `Bool` flags.

## Interview Questions About Swift Data Types

### Why does 0.1 + 0.2 not equal 0.3 in Swift?

`Double` stores binary fractions, and 0.1, 0.2 and 0.3 have no exact binary representation. The rounded values do not add up exactly, so compare with a tolerance or use integers or `Decimal` for exact decimal work.

### Why can't you index a String with an Int?

Characters are grapheme clusters of varying byte length, so reaching character *n* requires walking from the start. Swift makes that cost visible by requiring a `String.Index` instead of hiding a slow operation behind `[n]`.

### What happens when an Int overflows?

The program traps at run time, in debug and release builds, unless you use the wrapping operators such as `&+` or methods such as `addingReportingOverflow`. Overflow that the compiler can see is a build error.

### When would you choose Float over Double?

Only when an API or a file format requires it, or when memory for millions of values matters more than precision. `Double` is the default for decimal literals and the safer general choice.

## Try It Yourself

- Store three prices in cents as an array of `Int`: `1999`, `450` and `1258`.
- Add them up in a variable.
- Split the total into dollars and cents with `/` and `%`, and always show two digits for the cents.
- Store in a `Bool` whether the total is more than 30 dollars.
- Print the number of items, the total and the `Bool`.

**Expected output:** three lines, `Items: 3`, `Total: $37.07` and `Over $30: true`.

**Hint:** 3707 divided by 100 is 37 and the remainder is 7, which has to be printed as `07`.

**Solution:**

```swift
let pricesInCents = [1999, 450, 1258]

var totalCents = 0
for price in pricesInCents {
    totalCents += price
}

let dollars = totalCents / 100
let cents = totalCents % 100
let centsText = cents < 10 ? "0\(cents)" : "\(cents)"
let isOverLimit = totalCents > 3000

print("Items: \(pricesInCents.count)")
print("Total: $\(dollars).\(centsText)")
print("Over $30: \(isOverLimit)")
// Output:
// Items: 3
// Total: $37.07
// Over $30: true
```

Output (tested with Swift 6.4):

```text
Items: 3
Total: $37.07
Over $30: true
```

## Summary

- `Int`, `Double`, `String`, `Character` and `Bool` cover most values, and Swift never converts between them silently.
- `Int` is 64-bit on current Macs and iPhones; overflow stops the program, and integer division drops the fraction toward zero.
- `Double` is approximate: 0.1 + 0.2 prints 0.30000000000000004, so compare with a tolerance and keep money in integer cents or `Decimal`.
- A `Character` is one visible character, which can be several Unicode scalars; strings are counted in characters and cannot be indexed with integers.
- `Bool` is the only type a condition accepts, and `Bool("TRUE")` is `nil`.
- Text-to-number conversions return optionals; number-to-number conversions truncate.

Next, see how these types are stored in names that can or cannot change in [Swift variables and constants](/articles/swift/swift-variables-constants), or learn how Swift picks types for you in [Swift type inference](/articles/swift/swift-type-inference).
