With the contains
method, we can check if a range in Swift contains a particular value. If it does, a true
Boolean value is returned. Otherwise, a false
will be returned.
range.contains(value)
value
: This is the value we check to see if the range instance range
contains it.
The value returned is a Boolean. If the value value
is contained in the range instance range
, then true
is returned. Otherwise, false
is returned.
// create a rangelet range1 = 0 ..< 5 // 0 to 4// print each value in the rangeprint("Printing range elements: ")for value in range1 {print(value)}// check if range contains some valueprint("checking if range contains some value")print("1:", range1.contains(1)) // trueprint("5:", range1.contains(5)) // falseprint("10:", range1.contains(10)) // falseprint("3:", range1.contains(3)) // true
range1
.for-in
loop, we print all the values that are present in the range.contains()
method. We then print the results to the console.