Basic Operators
Comparison Operators
We can compare two tuples if they have same type and same number of values.
For example:
// true because 1 is less than 2; "zebra" and "apple" aren't compared
(1, "zebra") < (2, "apple")
// true because 3 is equal to 3, and "apple" is less than "bird"
(3, "apple") < (3, "bird")
// true because 4 is equal to 4, and "dog" is equal to "dog"
(4, "dog") == (4, "dog")
Tuples can be compared with given operator only if the operator can be applied to each value in the respective tuples.
For example:
// OK, evaluates to true
("blue", -1) < ("purple", 1)
// Error because < can't compare Boolean values
("blue", false) < ("purple", true)
Range Operators
Closed Range Operator
(a…b)
–>(a<=x<=b)
- means a range runs from
a
tob
- Including
a
andb
-
b
must be grater thana
for index in 1...5 {
print("\(index)")
}
// 1
// 2
// 3
// 4
// 5
Half-Open Range Operator
(a..<b)
-> (a<=x<b)
- means a range runs from
a
tob
- Including
a
, but not includingb
-
b
must be grater thana
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
One-Sided Ranges
An alternative writing for range operators.
(...5)
-> (0<=x<=5)
(..<5)
-> (0<=x<5)
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names[2...] { //means 2<=x<=count
print(name)
}
// Brian
// Jack
for name in names[...2] { //means 0<=x<=2
print(name)
}
// Anna
// Alex
// Brian
// we can handle range value as a object
let range = ...5
range.contains(7) // false
range.contains(4) // true
range.contains(-1) // true
let’s think!
网友评论