Swift编程入门(4)switch语句

2018/12/09 20:36 下午 posted in  Swift入门

之前见识了一种条件语句:if/else。在学习过程中曾提到,if/else对于不止一个条件的场景来说不太够用。本章就要来看看switch语句了。与if/else不同,switch非常适于处理多重条件。

什么是Switch

if/else语句会根据我们关注的条件是否为真来执行代码。与之对应的是,switch语句关注某个特殊的值,并将其与一系列分支(case)进行匹配;如果能匹配上,switch就会执行对应的代码。

switch aValue { 
case someValueToCompare: 
// 做一些响应操作
case anotherValueToCompare: 
// 做一些响应操作
default: 
// 没有匹配时的操作
} 

使用switch

写一个可以执行的Switch语句

import Cocoa

var statusCode: Int = 404
var errorString: String = ""
switch statusCode {
case 400:
    errorString = "Bad request"
case 401:
    errorString = "Unauthorized"
case 403:
    errorString = "Forbidden"
case 404:
    errorString = "Not found"
default:
    errorString = "None"
}

结果输出是:

Not found

上面的statusCode的值,和下面4个分支做了比较,最后因为404分支与statusCode匹配,所以errorString被赋值为"Not found"

另外switch分支也可以有多个值

import Cocoa
var statusCode: Int = 404
var errorString: String = "The request failed:"
switch statusCode {
case 400, 401, 403, 404:
    errorString = "There was something wrong with the request."
    fallthrough
default:
    errorString += " Please review the request and try again."
}

一个分支覆盖了所有的错误状态码(用逗号隔开了)。如果statusCode匹配了这个分支中的任何一个值,文本"There was something wrong with the request."就会被赋给
errorString。
fallthrough为状态转移语句(control transfer statement)。表示进入了这个分支后接着执行下一个分支(这里的就和其他语言比如PHP不一样了,php是需要break跳出这个switch,默认是执行default的)。

区间

switch语句也可以用valueX...valueY这样的语法来把某个区间内的值与给定值比较。

import Cocoa
var statusCode: Int = 404
var errorString: String = "The request failed with the error:"
switch statusCode {
case 100, 101:
    errorString += " Informational, 1xx."
case 204:
    errorString += " Successful but no content, 204."
case 300...307:
    errorString += " Redirection, 3xx."
case 400...417:
    errorString += " Client error, 4xx."
case 500...505:
    errorString += " Server error, 5xx."
default:
    errorString = "Unknown. Please review the request and try again."
}

上面的switch语句利用了区间匹配(range matching)语法...

值绑定

在某个特定分支中把待匹配的值绑定(bind)到本地的常量或变量上。这个常量或变量只能在该分支中使用。

import Cocoa
var statusCode: Int = 404
var errorString: String = "The request failed with the error:"

switch statusCode {
case 100, 101:
    errorString += " Informational, \(statusCode)."
case 204:
    errorString += " Successful but no content, 204."
case 300...307:
    errorString += " Redirection, \(statusCode)."
case 400...417:
    errorString += " Client error, \(statusCode)."
case 500...505:
    errorString += " Server error, \(statusCode)."
case let unknownCode:
    errorString = "\(unknownCode) is not a known error code."
default:
errorString = "\(statusCode) is not a known error code."
}

这里用了字符串插值来把statusCode传入每个分支的errorString。

where子句

where能让你额外检查一些条件,只有满足这些条件后才会匹配这个分支并绑定值。这个特性可以在switch中创建一些动态筛选条件。

import Cocoa
var statusCode: Int = 204
var errorString: String = "The request failed with the error:"
switch statusCode {
case 100, 101:
    errorString += " Informational, \(statusCode)."
case 204:
    errorString += " Successful but no content, 204."
case 300...307:
    errorString += " Redirection, \(statusCode)."
case 400...417:
    errorString += " Client error, \(statusCode)."
case 500...505:
    errorString += " Server error, \(statusCode)."
case let unknownCode where (unknownCode >= 200 && unknownCode < 300)
    || unknownCode > 505:
    errorString = "\(unknownCode) is not a known error code."
default:
    errorString = "Unexpected error encountered."
}

元组和模式匹配

import Cocoa
var statusCode: Int = 418
var errorString: String = "The request failed with the error:"
switch statusCode {
case 100, 101:
    errorString += " Informational, \(statusCode)."
case 204:
    errorString += " Successful but no content, 204."
case 300...307:
    errorString += " Redirection, \(statusCode)."
case 400...417:
    errorString += " Client error, \(statusCode)."
case 500...505:
    errorString += " Server error, \(statusCode)."
case let unknownCode where (unknownCode >= 200 && unknownCode < 300)
    || unknownCode > 505:
    errorString = "\(unknownCode) is not a known error code."
default:
    errorString = "Unexpected error encountered."
}
let error = (statusCode, errorString)

将statusCode和errorString放进一对圆括号就可以创建元组,结果被赋给error常量。
元组的元素可以用索引访问。你可能已经注意到在运行结果侧边栏中显示的元组的值带着.0.1,这就是元素的索引。

let error = (statusCode, errorString)
error.0 //418
error.1 //Unexpected error encountered.
// 也可以定义key值
let error = (code: statusCode, error: errorString)
error.code
error.error

使用元组做模式匹配

import Cocoa

let firstErrorCode = 404
let secondErrorCode = 200
let errorCodes = (firstErrorCode, secondErrorCode)
switch errorCodes {
case (404, 404):
    print("No items found.")
case (404, _):
    print("First item not found.")
case (_, 404):
    print("Second item not found.")
default:
    print("All items found.")
}

_表示是能匹配任何值的通配符

switch 与 if/else

switch语句主要用于比较一个值和多个潜在匹配的分支。if/else语句则对于检查单个的条件更有用。switch还提供一系列强大的特性,可以让你匹配区间、绑定值到本地常量或变量以及匹配元组中的模式。