加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 笔记(四)

发布时间:2020-12-14 07:14:42 所属栏目:百科 来源:网络整理
导读:我的主力博客:半亩方塘 Making Decisions 1、Consider this code: let number = 10switch (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 sy

我的主力博客:半亩方塘


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 thelet-wheresyntax,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 aspattern matching.

2、Another way you can useswitchstatements to great effect is as follows:

let coordinates: (x: Int,y: Int,z: Int) = (3,2,5)
switch (coordinates) {
case (0,0):
    print("Origin")
case (_,0):
    print("On the x-axis.")
case (0,_,0):
    print("On the y-axis.")
case (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 yourswitchstatement,like this:

let coordinates: (x: Int,0):
    print("Origin")
case (let x,0):
    print("On the x-axis at x = (x)")
case (0,let y,0):
    print("On the y-axis at y = (y)")
case (0,let z):
    print("On the z-axis at z = (z)")
case (let x,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,5)
switch(coordinates) {
case (let x,_) where y == x:
    print("Along the y = x line.")
case (let x,_) where y == x * x:
    print("Along the y = x^2 line.")
default:
    break
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读