Basic Operators

作者: 宋奕Ekis | 来源:发表于2021-07-22 11:17 被阅读0次

    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)

    1. means a range runs from a to b
    2. Including a and b
    3. b must be grater than a
    for index in 1...5 {
        print("\(index)")
    }
    // 1
    // 2
    // 3
    // 4
    // 5
    

    Half-Open Range Operator

    (a..<b) -> (a<=x<b)

    1. means a range runs from a to b
    2. Including a, but not including b
    3. b must be grater than a
    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!

    相关文章

      网友评论

        本文标题:Basic Operators

        本文链接:https://www.haomeiwen.com/subject/afpemltx.html