where更为有用,可用于检查关联类型是否必须确认位于where关键字之后的特定协议。
在开关情况下,添加和附加检查模式匹配也很有用。 最后,在switch语句的case标签,do语句的catch语句以及if,while,guard,for-in和条件类型的条件下可以使用where来定义类型约束。
var webUrl:字符串? =“ https://medium.com”
如果让path = webUrl where path.hasPrefix(“ https”){ //网站网址有效,请使用网站网址 }其他{ //网址无效,请在没有网址的情况下执行其他操作 }
在Swift 3.0之后,在这种情况下,您必须在何处使用逗号 (,) 。
var webUrl:字符串? =“ https://medium.com” 保护卫兵路径= webUrl 其中 path.hasPrefix(“ https”)否则{ //网址无效,请在没有网址的情况下执行其他操作 } //网站网址有效,请使用网站网址
var numArray:[Int]? = []
而让arr = numArray,arr.count <5 { numArray?.append(arr.count) }
print(numArray)// [0,1,2,3,4]
var numArray:[Int] = [0,1,2,3,4,5,6,7,8,9]
对于numArray中的val,其中(val%2 == 0){ 打印(val) } //打印0 2 4 6 8
枚举ValidationError:错误{ 案例RuntimeError(Int) }
func cryptoStrign(字符串:字符串,密码:字符串)抛出{ 如果string.characters.count == 0 { 抛出ValidationError.RuntimeError(10) } 否则,如果password.characters.count == 0 { 抛出ValidationError.RuntimeError(11) } }
做{ 尝试cryptoStrign(string:“我的秘密”,密码:“”) } 捕获ValidationError.RuntimeError(let errorCode),其中errorCode == 10 { print(“字符串为空”) }
捕获ValidationError.RuntimeError(let errorCode),其中errorCode == 11 { print(“密码为空”) //匹配 }
让yetAnotherPoint =(3,-3)
切换yetAnotherPoint {
设(x,y)其中x == y: print(“(\(x),\(y))在行x == y”)
设(x,y)其中x == -y: print(“(\(x),\(y))在行x == -y”) //匹配
设(x,y): print(“((\(x),\(y))只是任意点”) }
func doSomething (__ string:S),其中S:ExpressibleByStringLiteral { 打印(字符串) } doSomething(“ medium”)
//打印:中等
⚠️那些没有提到的场景可以用逗号替换。 您只能在哪里使用。
因此,在哪里很有用,可以以多种方式使用。