Home »
Swift »
Swift Programs
Swift program to demonstrate the one-sided range operator
Here, we are going to demonstrate the one-sided range operator in Swift programming language.
Submitted by Nidhi, on June 01, 2021
Problem Solution:
Here, we will create an array of strings and then access elements of the array using a one-sided range operator and print the result on the console screen.
The one-sided range operator is used to iterates range in one direction. It is an alternative form of closed range operator or half-open range operator.
Program/Source Code:
The source code to demonstrate a one-sided range operator is given below. The given program is compiled and executed successfully.
// Swift program to demonstrate the
// one sided range operator
let countries = ["india", "usa", "uk", "australia"]
let len = countries.count
print("Left sided range operator:")
for country in countries[1...] {
print("\t",country);
}
print("Right sided range operator:")
for country in countries[...2] {
print("\t",country);
}
Output:
Left sided range operator:
usa
uk
australia
Right sided range operator:
india
usa
uk
...Program finished with exit code 0
Press ENTER to exit console.
Explanation:
In the above program, we imported a package Swift to use the print() function using the below statement,
import Swift;
Here, we created an array of strings that contains the name of countries. Then we got the length of the array using the count property. After that, we accessed and printed the name of countries using a one-sided range operator on the console screen.
Swift Basic Programs »