欢迎来到代码驿站!

当前位置:首页 >

swift where与匹配模式的实例详解

时间:2021-03-24 10:30:05|栏目:|点击:

swift where与匹配模式的实例详解

前言:

在众多 Swift 提供给 Objective-C 程序员使用的新特性中,有个特性把自己伪装成一个无聊的老头,但是却在如何优雅的解决“鞭尸金字塔“的问题上有着巨大的潜力。很显然我所说的这个特性就是 switch 语句, 对于很多 Objective-C 程序员来说,除了用在 Duff's Device 上比较有趣之外,switch 语句非常笨拙,与多个 if 语句相比,它几乎没有任何优势。

1、基本使用

Swift中switch语句case后面可以用where对条件进行限制

let point = (3,3)
switch point{
case let (x,y) where x == y:
  print("It's on the line x == y!")
case let (x,y) where x == -y:
  print("It's on the line x == -y!")
case let (x,y):
  print("It's just an ordinary point.")
  print("The point is ( \(x) , \(y) )")
}

2、使用if - case - where语句替代switch语句的使用方法

let age = 19
switch age{
case 10...19:
  print("You're a teenager.")
default:
  print("You're not a teenager.")
}


if case 10...19 = age{
  print("You're a teenager.")
}

if case 10...19 = age where age >= 18{
  print("You're a teenager and in a college!")
}

注意:case条件必须放在”=”之前

swift 3.0以后if case 后面的”where”用”,”代替

3、if-case 与元组组合使用(元组解包使用)

let vector = (4,0)
if case ( let x , 0 ) = vector where x > 2 && x < 5{
  print("It's the vector!")
}

4、case - where 与循环组合使用

for i in 1...100{
  if i%3 == 0{
    print(i)
  }
}

for case let i in 1...100 where i % 3 == 0{
  print(i)
}

使用case限制条件可以大大减少代码量,使用起来非常方便,是swift语言的一大特色,好好掌握可以写出很优美的简洁的代码

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:深入浅析正则表达式中的\B和\b

栏    目:

下一篇:Powershell小技巧之通过EventLog查看近期电脑开机和关机时间

本文标题:swift where与匹配模式的实例详解

本文地址:http://www.codeinn.net/misctech/87118.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有