swift 从入门到精通

swift 从入门到精通 二

2019-11-06  本文已影响0人  TAsama

if-else

let age = 4
if age >= 22 {
  //to do
} else if age >= 18 {
  //to do
} else if age >= 7 {
  //to do
} else {
  //to do
}

while

var num = 5
while num > 0 {
  print("num is \(num)")
  num -= 1
}
var num = -1 
repeat {
  print("num is \(num)")
} while num > 0

for

let names = ["Anna", "Alex", "Brian", "Jack"]
for i in 0...3 {
  print(names[i])
} // Anna Alex Brian Jack
let range = 1...3
for i in range {
  print(names[i])
}
let a = 1
var b = 2
for i in a...b {
  print(names[i])
}
for i in a...3 {
  print(names[i])
}
// i默认是let,有需要时可以声明为var
for var i in 1...3 {
  i += 5
  print(i)
}// 6 7 8
for i in 1..<5 {
  print(i)
} // 1 2 3 4

for - 区间运算符用在数组上

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names[0...3] {
  print(name)
} // Anna Alex Brian Jack

单侧区间: 让区间朝一个方向尽可能的远

for name in names[2...] {
  print(name)
} // Brian Jack
for name in names[...2] {
  prin(name)
} // Anna Alex Brian
for name in names[..<2] {
  prin(name)
} // Anna Alex 

区间类型

let range1: ClosedRange<Int> = 1...3
let range2: Range<Int> = 1..<3
let range3: PartialRangeThrough<Int> = ...5

带间隔的区间值

let hours = 11
let hourInterval = 2
for tickMark in stride(from: 4, through: hours, by: hourInterval) {
  print(tickMark)
} // 4 6 8 10

switch

var number = 1
switch number {
  case 1:
    break
  case 2:
    break
  default:
    break
}

case后面必须有语句,否则报错。break可以不写,默认不穿透。如果需要穿透可以使用关键字“fallthrough”

var number = 1
switch number {
  case 1:
    fallthrough
  case 2:
    print("number is 2")
  default:
    print("number is other")
}
// number is 1
// number is 2

switch注意点

复合条件

let string = "Jack"
switch string {
  case "Jack":
    fallthrough
  case "Rose":
    print("Right person")
  default:
    break
}

使用复合条件代替fallthrough

let string = "Jack"
switch character {
  case "Jack", "Rose":
    print("Right person")
  default:
   break
} // Right person

区间匹配、元组匹配

let count = 62
switch count {
  case 0:
    print("none")
  case 1..<5:
    print("a few")
  case 5..<12:
    print("several")
  case 12..<100:
    print("dozens of")
  default:
    print("...")
}
let point = (1, 1)
switch point {
  case (0, 0):
    print("the origin")
  case (_, 0): // 前一个值无所谓,依据后一个值判断
    print("on the x-axis")
  case (-2...2, -2...2):
    print("inside the box")
}

值绑定

可以获取到元组中的值,用let或者中var来接收

let point = (2, 0)
switch point {
  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

接受条件判断

let point = (1, -1)
switch point {
  case let (x, y) where x == y:
    print("x == y")
  case let (x, y) where x == -y:
    print("x == -y")
  case let (x, y):
    print("\(x), \(y) is just some arbitrary point")
}
上一篇下一篇

猜你喜欢

热点阅读