我们一起聊聊Swift 条件控制和循环

开发 前端
本文我们介绍了 Swift 中 if/else, else if, switch 和 loops 语句等相关的知识。通过与 TypeScript 语法的对比,希望能帮助您更好地理解 Swift 的相关特性。

欢迎您阅读 Mastering Swift 基础教程,本文我们将介绍 Swift 中的变量、常量和数据类型。如果你尚未安装 Xcode 和配置 Swift 开发环境,请您先阅读这篇文章。

接下来,我们启动 Xcode,然后选择 "File" > "New" > "Playground"。创建一个新的 Playground 并命名为 "ConditionalsAndLoops"。

if...else

if-else 语句是一种常见的条件控制结构,用于根据条件的真假执行不同的代码块。

Swift Code

var temperature = 28

if temperature > 30 {
    print("It's a hot day")
} else {
    print("It's not so hot")
}

// Output: It's not so hot

TypeScript Code

let temperature = 28;

if (temperature > 30) {
    console.log("It's a hot day");
} else {
    console.log("It's not so hot");
}

// Output: "It's not so hot"

if...else if...else

if...else if...else 语句允许您按顺序处理多个条件。

Swift Code

let score = 85

if score >= 90 {
    print("Excellent!")
} else if score >= 80 {
    print("Good")
} else if score >= 70 {
    print("Average")
} else {
    print("Fail")
}

// Output: Good

TypeScript Code

const score: number = 85;

if (score >= 90) {
    console.log("Excellent!");
} else if (score >= 80) {
    console.log("Good");
} else if (score >= 70) {
    console.log("Average");
} else {
    console.log("Fail");
}

// Output: Good

switch

switch 语句是一种用于处理多个可能情况的流程控制结构。在 Swift 中,switch 语句可以用于处理各种数据类型,包括整数、浮点数、字符串 等。

Swift Code

let dayOfWeek = "Wednesday"

switch dayOfWeek {
case "Monday":
    print("Start of the workweek")
case "Tuesday", "Wednesday", "Thursday":
    print("Midweek, work in progress")
case "Friday":
    print("It's Friday, almost there!")
case "Saturday", "Sunday":
    print("Weekend vibes")
default:
    print("Invalid day")
}

// Output: Midweek, work in progress

相比 JavaScript 和 TypeScript,在 Swift case 分支中,无需使用 break 跳出分支。

TypeScript Code

const dayOfWeek: string = "Wednesday";

switch (dayOfWeek) {
  case "Monday":
    console.log("Start of the workweek");
    break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
    console.log("Midweek, work in progress");
    break;
  case "Friday":
    console.log("It's Friday, almost there!");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend vibes");
    break;
  default:
    console.log("Invalid day");
}

// Output: "Midweek, work in progress"

for-in

for-in 语句用于遍历集合(如数组、字典或范围)的循环结构。

Swift Code

for index in 1...5 {
    print("Index is \(index)")
}

/**
 Output:
 Index is 1
 Index is 2
 Index is 3
 Index is 4
 Index is 5
 */

在以上代码中,1...5 是一个闭区间运算符,表示一个包括从 1 到 5 的整数范围。这个范围包括 1 和 5 两个端点。

TypeScript Code

for (let index = 1; index <= 5; index++) {
    console.log(`Index is ${index}`);
}

/**
 Output:
 Index is 1
 Index is 2
 Index is 3
 Index is 4
 Index is 5
 */

在 Swift 中 for-in 循环还支持 where 子句,它可以更好地控制循环代码何时执行。

Swift Code

for index in 1...5 where index % 2 == 0 {
    print("Index is \(index)")
}

/**
 Output:
 Index is 2
 Index is 4
 */

while

while 语句是一种用于创建循环的控制流结构,只要给定条件为真,就会反复执行一段代码块。

Swift Code

var count = 1

while count <= 5 {
    print("Count is \(count)")
    count += 1
}

/**
 Output:
 Count is 1
 Count is 2
 Count is 3
 Count is 4
 Count is 5
 */

TypeScript Code

let count: number = 1;

while (count <= 5) {
    console.log(`Count is ${count}`);
    count++;
}

/**
 Output:
 Count is 1
 Count is 2
 Count is 3
 Count is 4
 Count is 5
 */

repeat-while

repeat-while 语句是一种循环结构,类似于 while 循环,不同之处在于 repeat-while 会先执行一次代码块,然后在满足条件的情况下重复执行。

Swift Code

var count = 1

repeat {
    print("Count is \(count)")
    count += 1
} while count <= 5

/**
 Output:
 Count is 1
 Count is 2
 Count is 3
 Count is 4
 Count is 5
 */

以上代码中,repeat-while 循环会先执行一次代码块,然后检查条件 count <= 5 是否仍然为真。只要条件为真,就会重复执行代码块。这确保了至少会执行一次,即使条件一开始就不满足。

在 TypeScript 中,目前并没有对应于 Swift 中 repeat-while 的语法。但可以通过 do-while 循环来实现类似的功能。

TypeScript Code

let count: number = 1;

do {
    console.log(`Count is ${count}`);
    count++;
} while (count <= 5);

/**
 Output:
 Count is 1
 Count is 2
 Count is 3
 Count is 4
 Count is 5
 */

本文我们介绍了 Swift 中 if/else, else if, switch 和 loops 语句等相关的知识。通过与 TypeScript 语法的对比,希望能帮助您更好地理解 Swift 的相关特性。


责任编辑:武晓燕 来源: 全栈修仙之路
相关推荐

2024-02-20 21:34:16

循环GolangGo

2023-12-28 09:55:08

队列数据结构存储

2023-05-31 08:42:02

管理产品技术项目

2022-04-07 11:43:24

UPnPDLNA协议

2021-08-27 07:06:10

IOJava抽象

2023-05-09 07:51:28

Spring循环依赖

2023-08-10 08:28:46

网络编程通信

2023-08-04 08:20:56

DockerfileDocker工具

2022-05-24 08:21:16

数据安全API

2023-06-30 08:18:51

敏捷开发模式

2023-09-10 21:42:31

2023-10-31 08:10:24

域名域名解析服务器

2022-02-14 07:03:31

网站安全MFA

2022-11-12 12:33:38

CSS预处理器Sass

2022-10-28 07:27:17

Netty异步Future

2023-04-26 07:30:00

promptUI非结构化

2022-06-26 09:40:55

Django框架服务

2022-01-04 12:08:46

设计接口

2022-04-06 08:23:57

指针函数代码

2022-12-07 13:12:15

点赞
收藏

51CTO技术栈公众号