Swift 笔记(四)

我的主力博客:半亩方塘


Making Decisions


1、Consider this code:

let number = 10
switch (number) {
case let x where x % 2 == 0:
    print("Even")
default:
    print("Odd")
}  


This will print the following:

Even

This switch statement uses the let-where syntax, meaning the case will match only when a certain condition is true. In this example, you've designed the case to match if the value is even-that is, if the value modulo 2 equals 0.

The method by which you can match values based on conditions is known as pattern matching.

2、Another way you can use switch statements to great effect is as follows:

let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)
switch (coordinates) {
case (0, 0, 0):
    print("Origin")
case (_, 0, 0):
    print("On the x-axis.")
case (0, _, 0):
    print("On the y-axis.")
case (0, 0, _):
    print("On the z-axis.") 
default:
    print("Somewhere in space")
}  

You're using the underscore to mean that you don't care about the value. If you don't want to ignore the value, then you can use it in your switch statement, like this:

let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)
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, let y, let z):
    print("Somewhere in space at x = \(x), y = \(y), z = \(z)")  
}  


You can use the same  let-where  syntax you saw earlier to match more complex cases. For example:

let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)
switch(coordinates) {
case (let x, let y, _) where y == x:
    print("Along the y = x line.")
case (let x, let y, _) where y == x * x:
    print("Along the y = x^2 line.")
default:
    break
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值