美文网首页
Swift基础(五)基本运算符 控制语句

Swift基础(五)基本运算符 控制语句

作者: 夕儿77 | 来源:发表于2021-12-01 13:22 被阅读0次

基本运算符

算术运算符

  • 加法(+
  • 减法(-
  • 乘法(*
  • 除法(/
  • 求余(%

比较运算符

  • 等于(a == b
  • 不等于(a != b
  • 大于(a > b
  • 小于(a < b
  • 大于等于(a >= b
  • 小于等于(a <= b

Swift 也提供恒等(===)和不恒等(!==)这两个比较符来判断两个对象是否引用同一个对象实例。

逻辑运算符

  • 逻辑非(!a
  • 逻辑与(a && b
  • 逻辑或(a || b

位运算符

  • 按位与(&
  • 按位或(|
  • 按位异或(^
  • 按位取反(~
  • 按位左移(<<
  • 按位右移(>>
// & 返回新数 1&1是1 其他是0
 1&1--> 1
 0&0--> 0
 0&1--> 0
 1&0--> 0
// | 返回新数 只有相同的0是0 其他是1
 1|1--> 1
 0|0--> 0
 0|1--> 1
 1|0--> 1
// ^ 返回新数 不同是1 相同是0
 1^1--> 0
 0^0--> 0
 0^1--> 1
 1^0--> 1
// ~ 返回新数 取相反 
 ~1-->0
 ~0-->1
// << >> 向左向右平移空出补0

赋值运算符

  • 等于( =
  • 加等( +=
  • 减等(-=
  • 乘等(*=
  • 除等(/=
  • 余等(%=
  • 按位左移后再赋值(<<=
  • 按位右移后再赋值(>>=
  • 按位与运算后赋值(&=
  • 按位异或运算符后再赋值(^=
  • 按位或运算后再赋值(|=

区间运算符

  • 闭区间运算符(a...b)定义一个包含从a到b(包括a和b)的所有值的区间
  • 半开区间(a..<b)定义一个从a到b但不包括b的区间

空合运算符

空合运算符a ?? b)将对可选类型 a 进行空判断,如果 a 包含一个值就进行解包,否则就返回一个默认值 b。表达式 a 必须是 Optional 类型。默认值 b 的类型必须要和 a 存储值的类型保持一致。

其他运算符

  • 一元减,数字前添加 - 号前缀。
  • 一元加,数字前添加 + 号前缀。
  • 三元运算符,condition ? X : Y

运算符优先级

  • 指针最优,单目运算优于双目运算。如正负号。
  • 先乘除(模),后加减。
  • 先算术运算,后移位运算,最后位运算。请特别注意:1 << 3 + 2 & 7 等价于 (1 << (3 + 2))&7。
  • 逻辑运算最后计算。

控制语句

  • Swift 的 switch 语句比许多类 C 语言要更加强大。case 还可以匹配很多不同的模式,包括范围匹配,元组(tuple)和特定类型匹配。switch 语句的 case 中匹配的值可以声明为临时常量或变量,在 case 作用域内使用,也可以配合 where 来描述更复杂的匹配条件。

For-In 循环

// 使用 `for-in` 循环来遍历一个集合中的所有元素。
// 数组
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}
// 字典
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
// 数字范围
// index 是一个每次循环遍历开始时被自动赋值的常量
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 不需要区间序列内每一项的值
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")

While 循环

  • 这类循环适合使用在第一次迭代前,迭代次数未知的情况下。
  • while 循环会一直运行一段语句直到条件变成 false
  • while 循环,每次在循环开始时计算条件是否符合。
  • repeat-while 循环,每次在循环结束时计算条件是否符合。
// While的格式
while condition {
    statements
}
// repeat-while 循环的一般格式 Swift 语言的 repeat-while 循环和其他语言中的 do-while 循环是类似的。
repeat {
    statements
} while condition

条件语句

if
  • if 判断语句,当条件较为简单且可能的情况很少时,使用 if 语句。
// if 语句
if boolean_expression {
   /* 如果布尔表达式为真将执行的语句 */
}

// if...else 语句
if boolean_expression {
   /* 如果布尔表达式为真将执行的语句 */
} else {
   /* 如果布尔表达式为假将执行的语句 */
}

// if...else if...else
if boolean_expression_1 {
   /* 如果 boolean_expression_1 表达式为 true 则执行该语句 */
} else if boolean_expression_2 {
   /* 如果 boolean_expression_2 表达式为 true 则执行该语句 */
} else {
   /* 如果以上所有条件表达式都不为 true 则执行该语句 */
}

// 嵌套 if 语句
if boolean_expression_1 {
   /* 当 boolean_expression_1 表达式 true 时执行 */
   if boolean_expression_2 {
      /* 当 boolean_expression_1 表达式 true 时执行 */
   }
}
Switch
  • Switch更适用于条件较复杂、有更多排列组合的时候。
  • switch 语句会尝试把某个值与若干个模式(pattern)进行匹配。
  • switch 语句必须是完备的。这就是说,每一个可能的值都必须至少有一个 case 分支与之对应。
  • 不需要在 case 分支中显式地使用 break 语句。
// switch 语句最简单的形式就是把某个值与一个或若干个相同类型的值作比较:
var index = 10
switch index {
   case 100  :
      print( "index 的值为 100")
   case 10,15  :
      print( "index 的值为 10 或 15")
   case 5  :
      print( "index 的值为 5")
   default :
      print( "默认 case")
}

//Fallthrough  如果使用了Fallthrough 语句,则会继续执行之后的 case 或 default 语句,不论条件是否满足都会执行。
var index = 10
switch index {
   case 100  :
      print( "index 的值为 100")
      fallthrough
   case 10,15  :
      print( "index 的值为 10 或 15")
      fallthrough
   case 5  :
      print( "index 的值为 5")
   default :
      print( "默认 case")
}

// 每一个 case 分支都必须包含至少一条语句。 
// 这段代码会报编译错误
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // 无效,这个分支下面没有语句
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}

// case 分支的模式也可以是一个值的区间
let approximateCount = 62
let naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("\(naturalCount).") // 输出 dozens of”

// 使用元组在同一个 switch 语句中测试多个值 如果存在多个匹配,那么只会执行第一个被匹配到的 case 分支
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (0, _):
    print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box") } // 输出“(1, 1) is inside the box”
default:
    print("\(somePoint) is outside of the box")
} 

//case 分支允许将匹配的值声明为临时常量或变量,并且在 case 分支体内使用 —— 这种行为被称为值绑定(value binding),因为匹配的值在 case 分支体内,与临时的常量或变量绑定。
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}// 输出“on the x-axis with an x value of 2”

// Where case 分支的模式可以使用 `where` 语句来判断额外的条件。
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
    print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
    print("(\(x), \(y)) is just some arbitrary point")
}// 输出“(1, -1) is on the line x == -y”

//复合型 Cases  两个值组合成一个复合匹配,并且用逗号分开:
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
     "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    print("\(someCharacter) is a consonant")
default:
    print("\(someCharacter) is not a vowel or a consonant")
}// 输出“e is a vowel”

// 使用元祖的复合语句
let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
    print("On an axis, \(distance) from the origin")
default:
    print("Not on an axis")
}
// 输出“On an axis, 9 from the origin”

控制转移语句

  • continue
  • break
  • return
  • throw
Continue
  • continue` 语句告诉一个循环体立刻停止本次循环,重新开始下次循环。
var index = 10
repeat{
   index = index + 1
   if( index == 15 ){ // index 等于 15 时跳过
      continue
   }
   print( "index 的值为 \(index)")
}while index < 20 
Break
  • break 语句会立刻结束整个控制流的执行。break 可以在 switch 或循环语句中使用,用来提前结束 switch 或循环语句。
  • 当在一个循环体中使用 break 时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(})后的第一行代码。不会再有本次循环的代码被执行,也不会再有下次的循环产生。
  • 当在一个 switch 代码块中使用 break 时,会立即中断该 switch 代码块的执行,并且跳转到表示 switch 代码块结束的大括号(})后的第一行代码。
import Cocoa
var index = 10
repeat{
    index = index + 1
    if( index == 15 ){  // index 等于 15 时终止循环
        break
    }
    print( "index 的值为 \(index)")
}while index < 20
提前退出
  • if 语句一样,guard 的执行取决于一个表达式的布尔值。我们可以使用 guard 语句来要求条件必须为真时,以执行 guard 语句后的代码。不同于 if 语句,一个 guard 语句总是有一个 else 从句,如果条件不为真则执行 else 从句中的代码。
func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }
    print("Hello \(name)!")
    guard let location = person["location"] else {
        print("I hope the weather is nice near you.")
        return
    }
    print("I hope the weather is nice in \(location).")
}

greet(person: ["name": "John"])
// 输出“Hello John!”
// 输出“I hope the weather is nice near you.”
greet(person: ["name": "Jane", "location": "Cupertino"])
// 输出“Hello Jane!”
// 输出“I hope the weather is nice in Cupertino.”

相关文章

网友评论

      本文标题:Swift基础(五)基本运算符 控制语句

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