where 條件約束
var eHttpCode:(Int, String) = (404, "Not Found")
switch eHttpCode
{
/// where 約束 eCode在 [200, 300) 時(shí):
case let (eCode, _) where eCode >= 200 && eCode < 300:
print("---當(dāng)eCode在[200, 300)才 輸出 --")
default:
print("Bad request.")
}
let eArrInt = [24, 32, 30, 36, 28, 33]
/// where 約束 eArrInt 中的元素 >= 31 時(shí)才遍歷輸出:
for eI in eArrInt where eI >= 31
{
print("---where 約束 eArrInt 中的元素 >= 31 時(shí)才遍歷輸出: \(eI)--") //32,36,33
}
// where 約束 泛型 T類型 必須遵循 Decodable協(xié)議:
func getDecodableResult<T>(eT : T) where T : Decodable
{
print(eT)
}
enum HTTPError : Error
{
case code(Int)
}
do
{
try requestWithError()
}
catch HTTPError.code(let code) where code == 408
{
print("Request time out.")
}
func requestWithError() throws
{
throw HTTPError.code(400)
}
- where 和 associatedtype 搭配使用:
// where 和 associatedtype 搭配使用:
protocol EProtocolA
{
associatedtype eA : IteratorProtocol
associatedtype eB : Sequence where eB.Iterator.Element == eA.Element
// eB遵循Sequence協(xié)議, 且 where 約束 eB中的元素須和eA的元素類型一樣;
}
// where 約束 對(duì)遵循EProtocolA協(xié)議的同時(shí)斟珊,且遵循Equatable協(xié)議 的類型進(jìn)行擴(kuò)展:
extension EProtocolA where Self : Equatable
{
func yeTest()
{
print("---where 約束 對(duì)遵循EProtocolA協(xié)議的同時(shí)蜡歹,且遵循Equatable協(xié)議 的類型進(jìn)行擴(kuò)展:--")
}
}
截屏2023-01-24 22.50.41.png
截屏2023-01-24 22.50.57.png
截屏2023-01-24 22.51.12.png
截屏2023-01-24 22.51.14.png
截屏2023-01-24 22.51.27.png
截屏2023-01-24 22.51.41.png
截屏2023-01-24 22.51.47.png
截屏2023-01-24 22.51.57.png
截屏2023-01-24 22.52.05.png
截屏2023-01-24 22.52.13.png