Swift学习这十二:(续)控制流

// 值绑定(Value Binding)
let anotherPoint = (2, 0)
// 这就是所谓的值绑定,通过值赋给临时常量或者变量
switch anotherPoint {
  case (let x, 0): // 这里不需要修改x的值,所以声明为let,即常量
    println("on the x-axis with an x value of \(x)")
  case (0, let y):
    println("on the y-axis with a y value of \(y)")
  case let (x, y): // 对于这里,没有使用Default,其实这里这么写法就相当于default:
    println("somewhere else at (\(x), \(y))")  
}

// 使用where语句来检测额外的条件
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
  case let (x, y) where x == y: // 使用值绑定,要求x与y相等
    println("(\(x), \(y)) is on the line x == y")
  case let (x, y) where x == -y:// 使用值绑定,要求x与-y相等
    println("(\(x), \(y)) is on the line x == -y") 
  case let (x, y):// 使用值绑定,相当于default
    println("(\(x), \(y)) is just some arbitrary point") 
}

/*
  continue
  break
  falthrough
  return
*/
// continue、break、return跟C、OC中的continue、break、return是一样的
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for c in puzzleInput {
  switch c {
    case "a", "e", "i", "o", "u", "":// 相当于遇到这几种字符就会就会继续循环而不往下执行
	   continue
	default:
       puzzleOutput += c	
  }
}

let numberSymbol: Character = "三"
var possibleIntegerValue: Int?
switch numberSymbol {
  case "1", "一":
    possibleIntegerValue = 1
  case "2", "二"	
  default:
    break
}

let integerToDescribe = 5
var descripton = "The number \(integerToDescribe) is"
switch integerToDescribe {
  case 2, 3, 5, 7, 9, 11, 13, 17, 19:
    descripton += "a prime number, and also"
	falthrough // 加上falthrough,就会继续往下执行,执行default这里的语句
  default:
	descripton += " an integer"
}
// print: The number 5 is a prime number, and also an integer 

// 可以给循环添加标签
var integerValue = 0
let count = 10
GameLoopLabel: while integerValue < count {
  switch integerValue {
    case integerValue % 2 == 0: 
	  break GameLoopLabel // 调用此语句后,就退出了while循环
	case let inValue where (inValue > 5 && inValue % 2 != 0):
	  continue GameLoopLabel
	default:
	  println("run default")
	  break GameLoopLabel
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值