swift
Range
Int
conversion
array

swift convert RangeInt to Int

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

A Range<Int> in Swift is not a single integer — it represents a sequence of integers between a lower and upper bound. Converting it to an [Int] array uses Array(range). To extract a single integer from a range, access specific properties like lowerBound, upperBound, or count. The conversion approach depends on whether you need all values in the range, just the bounds, or a random element.

Range to Array

swift
1// Half-open range (..<) — excludes upper bound
2let range = 0..<5
3let array = Array(range)
4print(array) // [0, 1, 2, 3, 4]
5
6// Closed range (...) — includes upper bound
7let closedRange = 1...5
8let closedArray = Array(closedRange)
9print(closedArray) // [1, 2, 3, 4, 5]

Array(range) iterates over the range and collects each integer into an array.

Accessing Bounds

swift
1let range = 10..<20
2
3let lower: Int = range.lowerBound  // 10
4let upper: Int = range.upperBound  // 20 (exclusive)
5let count: Int = range.count       // 10
6
7// For ClosedRange
8let closed = 10...20
9let closedUpper: Int = closed.upperBound  // 20 (inclusive)
10let closedCount: Int = closed.count       // 11

Random Element from Range

swift
1let range = 1...100
2
3// Single random integer from the range
4let randomInt: Int = Int.random(in: range)
5print(randomInt) // Random number between 1 and 100
6
7// Or using randomElement()
8if let element = range.randomElement() {
9    print(element)
10}

Mapping a Range

swift
1// Map range to transformed values
2let squares = (1...5).map { $0 * $0 }
3print(squares) // [1, 4, 9, 16, 25]
4
5// Filter from a range
6let evens = (1...10).filter { $0 % 2 == 0 }
7print(evens) // [2, 4, 6, 8, 10]
8
9// Reduce a range to a single value (sum)
10let sum = (1...100).reduce(0, +)
11print(sum) // 5050

Ranges conform to Sequence, so map, filter, and reduce work directly without converting to an array first.

Iterating Over a Range

swift
1// for-in loop — no array conversion needed
2for i in 0..<5 {
3    print(i) // 0, 1, 2, 3, 4
4}
5
6// forEach
7(1...5).forEach { print($0) }
8
9// stride for custom steps
10for i in stride(from: 0, to: 20, by: 3) {
11    print(i) // 0, 3, 6, 9, 12, 15, 18
12}

Range with Collection Subscripts

swift
1let names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
2
3// Use a range to slice an array
4let subset = names[1..<3]
5print(Array(subset)) // ["Bob", "Charlie"]
6
7// Get indices as a range
8let validIndices = names.indices // 0..<5
9print(validIndices.lowerBound) // 0
10print(validIndices.upperBound) // 5

Converting Between Range Types

swift
1// ClosedRange to Range (half-open)
2let closed: ClosedRange<Int> = 1...5
3let halfOpen: Range<Int> = closed.lowerBound..<(closed.upperBound + 1)
4print(halfOpen) // 1..<6
5
6// Range to ClosedRange (only if non-empty)
7let range: Range<Int> = 1..<6
8if !range.isEmpty {
9    let closedRange: ClosedRange<Int> = range.lowerBound...(range.upperBound - 1)
10    print(closedRange) // 1...5
11}

Using Ranges with String Indices

swift
1let str = "Hello, World!"
2
3// String ranges use String.Index, not Int
4let start = str.index(str.startIndex, offsetBy: 7)
5let end = str.index(str.startIndex, offsetBy: 12)
6let substring = str[start..<end]
7print(substring) // "World"
8
9// Convert character positions to Int
10let charCount = str.distance(from: str.startIndex, to: end)
11print(charCount) // 12

NSRange and Swift Range Conversion

swift
1import Foundation
2
3let str = "Hello, World!"
4
5// Swift Range to NSRange
6let swiftRange = str.range(of: "World")!
7let nsRange = NSRange(swiftRange, in: str)
8print(nsRange) // {7, 5}
9
10// NSRange to Swift Range
11if let swiftRange = Range(nsRange, in: str) {
12    print(str[swiftRange]) // "World"
13}

Checking if a Value Is in a Range

swift
1let range = 1...100
2
3// contains
4print(range.contains(50))  // true
5print(range.contains(101)) // false
6
7// Pattern matching with ~=
8if 1...100 ~= 42 {
9    print("42 is in range")
10}
11
12// Switch statement
13let score = 85
14switch score {
15case 90...100: print("A")
16case 80..<90:  print("B")
17case 70..<80:  print("C")
18default:       print("F")
19}
20// Output: B

Common Pitfalls

  • Empty ranges: 5..<5 is an empty range (no elements). Array(5..<5) returns []. 5..<4 is invalid and crashes at runtime.
  • ClosedRange vs Range: 1...5 has 5 elements; 1..<5 has 4. Off-by-one errors are the most common range bug.
  • Large ranges: Array(0..<1_000_000_000) allocates 8 GB of memory (1 billion Int64 values). Use ranges directly in for loops or lazy sequences instead of converting to arrays.
  • String indices are not Int: Swift strings use String.Index, not Int. You cannot write str[0..<5]. Use str.index(str.startIndex, offsetBy: n) to convert.
  • Range is not RandomAccessCollection for all types: Range<Int> supports random access. Range<String.Index> does not — you cannot jump to an arbitrary position without iterating.

Summary

  • Use Array(range) to convert a Range<Int> to [Int]
  • Access .lowerBound, .upperBound, and .count to extract integers from a range
  • Use Int.random(in: range) for a random integer from a range
  • Ranges support map, filter, reduce, and for-in directly without array conversion
  • Use stride(from:to:by:) for ranges with custom step sizes
  • Convert between Range and NSRange with NSRange(_:in:) and Range(_:in:)

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.