Swift控制流和简单模式匹配介绍

Swift控制流和简单模式匹配介绍

代码和注释

如果喜欢请告诉我,我会继续发表其他内容在csdn,希望大家可以一起进步

// ---------------------
// |if语句,复合情况逗号分隔|
// ---------------------
// if语句中可以将可选值绑定,布尔限定语句,case let|var 模式匹配混合使用.
var temperatureInFahrenheit: Int? = 90
if case let temperatureInFahrenheit? = temperatureInFahrenheit, temperatureInFahrenheit <= 32, temperatureInFahrenheit >= 0 {
    print("It's really warm. Don't forget to wear sunscreen. \(temperatureInFahrenheit).")
} else if case let temperatureInFahrenheit? = temperatureInFahrenheit,  temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}
// prints "It's really warm. Don't forget to wear sunscreen."

// ----------
// |While循环|
// ----------
let array = [1, 2, 3, nil]
var iterator = array.makeIterator()
//while语句中可以将可选值绑定,布尔限定语句,case let|var 模式匹配混合使用.
while let i = iterator.next() {
    print(i, terminator:" ")// iterator.next()返回值双重可选值
}

repeat {
    temperatureInFahrenheit = -1

} while temperatureInFahrenheit ?? -1 >= 0

// ⭐️ for和while循环中  每次迭代时 i 都是一个新的局部变量,避免了变量捕获造成的bug。

// ------------
// |for-in 循环|
// ------------
// for-in 循环 其实就是while循环加上一个迭代器的简写方式。

// 如果只想对非nil值作for循环可以使用 case let|var 来进行模式匹配。语法糖.some(i)
for case let i? in array where i > 0 {//⭐️ 这里的 where分句 不同于 if和while语句 的 逗号分句表达式,一旦false迭代不会停止,只会跳过这个条件。
    print(i, terminator:" ")
}

for case nil in array {//只对匹配 nil的值 进行循环
    print("No value!")
}

//for-in 循环中还可以循环 字典、区间、 stride(from:through:by:)和stride(from:to:by:) 函数等
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}

// --------------------
// |switch 语句 复合情况|
// --------------------
// 复合情况同样可以包含值绑定。这些值绑定必须是相同的集合(最高要求 ———— 值绑定整体类型不同就不是相同集合),满足前面的要求下,接下来每一个绑定集合中的绑定值必须是相同类型即可。
let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
    case (1, let distance):
        print("123"+"\(distance)")
    case (let distance, 0), (1, let distance):
        print("On an axis, \(distance) from the origin")
    default:
        print("Not on an axis")
}


// --------------
// |case 模式匹配|
// --------------
// case 模式匹配 可以通过重载 ~=运算符 来进行扩展以匹配不同的类型。
let j = 5
//已有的类型不需要扩展
if case 0 ..< 10 = j {
    print("\(j) 在范围内")
}// 5 在范围内

struct Substring {
    let s: String
    init(_ s: String) {
        self.s = s
    }
}

func ~=(pattern: Substring, value: String) -> Bool {
    return value.range(of: pattern.s) != nil
}

let s = "Taylor Swift"
if case Substring.init("Swift") = s {
    print("拥有 \"Swift\" 后缀")
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值