美文网首页
swift 4 高级流程控制

swift 4 高级流程控制

作者: 艺术农 | 来源:发表于2018-05-30 17:01 被阅读16次
  • Countable Range
    闭区间和半开半闭区间
let closedRange = 0...5
//012345
for i in closedRange {
   print(i)
}

let halfOpenRange = 0..<5
//01234
for i in halfOpenRange {
    print(i)
}
  • 不需要循环常数
    不需要使用循环索引时,可以用下划线替代
sum = 1
var lastSum = 0

for _ in 0..<count {
    let temp = sum
    sum = sum + lastSum
    lastSum = temp
} 
  • 指定条件的loop
    使用where关键字
sum = 0
for i in 1...count where i % 2 == 1 {
    sum += 1
}
  • case语法
  1. 多case情况
let hourOfDay = 12
let timeOfDay: String

switch hourOfDay {
case 0, 1, 2, 3, 4, 5:
  timeOfDay = "Early morning"
case 6, 7, 8, 9, 10, 11:
  timeOfDay = "Morning"
case 12, 13, 14, 15, 16:
  timeOfDay = "Afternoon"
case 17, 18, 19:
  timeOfDay = "Evening"
case 20, 21, 22, 23:
  timeOfDay = "Late evening"
default:
  timeOfDay = "INVALID HOUR!"
}

print(timeOfDay)
  1. ranges应用在case
switch hourOfDay {
case 0...5:
  timeOfDay = "Early morning"
case 6...11:
  timeOfDay = "Morning"
case 12...16:
  timeOfDay = "Afternoon"
case 17...19:
  timeOfDay = "Evening"
case 20..<24:
  timeOfDay = "Late evening"
default:
  timeOfDay = "INVALID HOUR!"
}
  1. 条件语法结合case使用
switch number {
case let x where x % 2 == 0:
  print("Even")
default:
  print("Odd")
}

省略常数x

switch number {
case _ where number % 2 == 0:
  print("Even")
default:
  print("Odd")
}
  • 部分匹配(Partial matching)
let coordinates = (x: 3, y: 2, z: 5)

switch coordinates {
case (0, 0, 0): // 1
  print("Origin")
case (_, 0, 0): // 2
  print("On the x-axis.")
case (0, _, 0): // 3
  print("On the y-axis.")
case (0, 0, _): // 4
  print("On the z-axis.")
default:        // 5
  print("Somewhere in space")
}
switch coordinates {
case (0, 0, 0):
  print("Origin")
case (let x, 0, 0):
  print("On the x-axis at x = \(x)")
case (0, let y, 0):
  print("On the y-axis at y = \(y)")
case (0, 0, let z):
  print("On the z-axis at z = \(z)")
case let (x, y, z):
  print("Somewhere in space at x = \(x), y = \(y), z = \(z)")
}
switch coordinates {
case let (x, y, _) where y == x:
  print("Along the y = x line.")
case let (x, y, _) where y == x * x:
  print("Along the y = x^2 line.")
default:
  break
}

相关文章

网友评论

      本文标题:swift 4 高级流程控制

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