Swift ranges: How you can work with it in iOS development

Can’t help but mention Swift ranges when you want to work well with Swift programming language. If you are following the previous articles of ArrowHiTech, you may know Swift is one of the well-known and greatest languages in the world. In order to continue our series of blogs about Swift’s features, let’s come to Swift ranges. With anyone without any knowledge of Swift ranges, this blog is very beneficial for them. Then, let’s explore it right now!

What are Swift ranges?

Swift ranges

In order to work well with Swift ranges, firstly, you should understand its definition in detail. For more details, Swift ranges are the advanced features of Swift programming language. Ranges are used to describe values between a lower and higher limit in Swift. In particular, they can be used to create array slices, verify if a value is within a range and so on. 

Specifically, Swift ranges are a set of values that span two numeric intervals. Then, let’s take a look at the syntax below:

Swift ranges code

Types of Swift ranges

Swift language separates into three types of Swift ranges. Let’s explore each one. 

#1. Closed Swift range

Closed range is a type where all of the numbers in the interval between the lower and upper bounds are included in it. 

Let’s refer to the following example

// 1…4 is close range

for numbers in 1…4 {

  print(numbers)

}

As soon as you follow this instruction above, you will get the outcome like:

Closed Swift range

As you probably see, we’ve constructed a confined range 1…4 in the instance above.

It includes all the numbers between 1 and 4, including the bottom bound (1) and upper bound (2), because it is a closed range (4).

Besides, to access all of the values in the range, we used the Swift for loop.

#2. Half-Open Range

Coming to the second type of Swift ranges – Half-Open range. In fact, the half-open range encompasses all values between the lower and upper bounds. On the other hand, it doesn’t include the upper limitation. What’s more, the ..< operator is used to declare it. So, look at the example below and you will understand this with ease:

for numbers in 1..<4 {

  print(numbers)

}

Then, the result you get is:

codes

#3. One-sided Range

The last type of Swift ranges is One-sided Range. For more details, using either the … or the ..< operator, we can make a one-sided range. In one direction, a one-sided range contains elements up to infinite. Then, you can know about this thanks to the example below:

let range1 = ..<2

Specifically, in this case, …<2 plays a role as a one-sided Swift range. Also, it includes all components ranging from 2 to  -∞. Besides, as similar as that, the range includes all components between 2 and +∞.

let range2 = 2…

What’s more, through looking for a certain number in the range, we may validate this. Then, let’s have a glance at the instance below:

// one-sided range using 

// ..< operator

let range1 = ..<2

// check if -9 is in the range

print(range1.contains(-1))

// one-sided range using

// … operator

let range2 = 2…

// check if 33 is in the range

print(range2.contains(33))

Applying the codes above, then, you will receive the output like:

 One-sided Swift Ranges

In reality, in this case, we’ve used the contains() method to determine if a specific number is in the range.

Way to work well with Swift ranges in iOS development

How to work with Ranges and Arrays?

To begin, why don’t you start putting those ranges to work? Coming to the first case that is one of the most common ones is Swift ranges and arrays. Ranges are frequently used in conjunction with arrays in practical app development. 

Let’s refer to the following codes:

let names = [“Bernard”, “Dolores”, “Maeve”, “Lee”]

for i in 0..<names.count {

    print(names[i])

}

As you can see, using a for loop, we iterate over the names array of strings in the example above. Rather than directly iterating the array, we’ll create a range and utilize it to retrieve specific array objects by key.

The range we’re working with is 0..<names.count, which means from 0 to 4, except 0, 1, 2, and 3. The indices in the array are represented by the integers in the range.

Moreover, within the for loop, we use subscript syntax to access specific array objects using the array index – the integer from within the range. In addition, when i equals 2 at any point throughout the loop, we print out “Maeve”, for instance.

Of course, we’re not utilizing the easier for name in names syntax here for the benefit of this case. Iterating collections and ranges with indices is a popular practice in real iOS development. Consider binary search or insertion sort, both of which work directly with array indices and the ranges that include them.

Array Slicing with Swift Ranges

In fact, that thing above isn’t the only thing that ranges are useful for. Range operators can be used to extract pieces of an array, which is referred to as a slice. In order to know, let’s take a look at this: 

let names = [“Ford”, “Arthur”, “Zaphod”, “Marvin”, “Eddie”]

let slice = names[0…2]

print(slice)

Let’s analyze the lines of code above:

We’ve defined an array of strings called names in the code above. We’re “selecting” a subset of that array with the closed range operator, namely elements 0, 1, and 2. [“Ford”, “Arthur”, “Zaphod”] is printed out as a consequence. 

Furthermore, the outstanding thing is that the slice constant’s type is ArraySlice<String>. In particular, it isn’t an array as well as not a duplicate of the names array. A slice, on the other hand, is a transient “view” into the source names array.

Additionally, a slice can be thought of as an index-only replica of the array that refers to the old names array. If necessary, Swift will convert the slice to an actual Array type, or you can use the Array(···) initializer manually.

How to use Swift Ranges with Strings?

In fact, Swift strings are a little strange. Strings can be treated as if they were character arrays in many computer languages. In Swift, this isn’t possible. So, let’s take a look at below:

let name = “Reinder”

print(name[2])

Simply speaking, the above code should print “i” which is the third character in the string. Besides, it doesn’t work that way for several reasons, the most notable of which is that Swift strings are encoded as UTF-8, which is a variable width encoding. 

Above all, you can’t calculate the index of any character in Swift string because Swift characters don’t have a defined width. Not only that, depending on the length of the individual characters in the string, you may wind up with characters 5 to 9 when you say “Get me the 7th character!”

What’s more, thanks to offering indices-compatible string APIs, Swift can solve this problem. These indices can be increased in steps by “walking” or “striding” them. Swift determines if stepping over one or several bytes is required for the next index. You can use regular range operators once you’ve constructed indices.

So, let’s refer to the following instance:

let text = “The lazy dog jumped over the quick brown fox”

let start = text.index(text.startIndex, offsetBy: 4)

let end = text.index(text.startIndex, offsetBy: 8)

print(text[start..<end])

After following the lines of code above, you may see that we’ve defined a string named text. Besides, to calculate the indices of the string, we use the index( :offsetBy:) function. Moreover, this works by choosing a starting index and counting n steps from there. The half-open range operator.. is then used to select the characters “lazy” from the string.

The final line

What do you think about the information of Swift ranges ArrowHiTech delivers through this blog? In fact, we hope it will be useful for you to work effectively on the iOS platform. In particular, during the process of running Swift ranges, in case you’re facing any difficulty, you should ask ArrowHiTech for help. We believe with 13+ years in the technology area as well as Swift and Objective-C IOS App Development Services, we can help you solve everything about Swift.

Tags

Share