The Swift Programming Language--Basic Operators

Basic Operators

  • Assignment Operator
    let (x, y) = (1, 2)

  • Arithmetic Operators
    let str = "Hello" + "World" // '+' operator

Remainder Operator. The sign of b is ignored for negative values of b. This means that a%b and a%-b always give the same answer.

  let remains = 8%2.5 // 0.5

++ and -- can be used for any integer and floating-point type.

  let minusSix = -6
  let alsoSix = +minusSix // -6, '+' does not do anything
  • Nil Coalescing Operator
    a ?? b // a is optional, b is the actual type of a
    a != nil ? a! : b

    let str: String = "Hello"
    var str1: String?// default set to nil
    
    var str2 = str1 ?? str // Hello, since str1 is nil
    
  • Range Operator
    for i in 1...5 {
    print(i)
    }//1 2 3 4 5

    for i in 1..<5 {
       print(i)
    }// 1 2 3 4
    

你可能感兴趣的:(The Swift Programming Language--Basic Operators)