Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Range Operators in Swift
Written by Team Kodeco

Swift provides two range operators that can be used to create ranges of values and check if a value falls within a range. The range operators in Swift are:

  • ... for closed range (includes the last value).
  • ..< for half-open range (excludes the last value).

Here’s an example:

// Closed range: includes the last value)
for num in 1...3 {
  print(num, terminator: " ")
}
// Output: 1 2 3 

// Half-open range: excludes the last value
for num in 1..<3 {
  print(num, terminator: " ")
}
// Output: 1 2 

Checking if a Range Contains a Value

You can use contains to check if a value falls within a range:

let a = 5
let range = 1...10

print(range.contains(a)) // true
print(range.contains(0)) // false
© 2024 Kodeco Inc.