我们一起聊聊Swift 条件控制和循环
创始人
2025-07-11 03:11:45
0

欢迎您阅读 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 的相关特性。


相关内容

热门资讯

PHP新手之PHP入门 PHP是一种易于学习和使用的服务器端脚本语言。只需要很少的编程知识你就能使用PHP建立一个真正交互的...
网络中立的未来 网络中立性是什... 《牛津词典》中对“网络中立”的解释是“电信运营商应秉持的一种原则,即不考虑来源地提供所有内容和应用的...
各种千兆交换机的数据接口类型详... 千兆交换机有很多值得学习的地方,这里我们主要介绍各种千兆交换机的数据接口类型,作为局域网的主要连接设...
什么是大数据安全 什么是大数据... 在《为什么需要大数据安全分析》一文中,我们已经阐述了一个重要观点,即:安全要素信息呈现出大数据的特征...
如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
P2P的自白|我不生产内容,我... 现在一提起P2P,人们就会联想到正在被有关部门“围剿”的互联网理财服务。×租宝事件使得劳...
Intel将Moblin社区控... 本周二,非营利机构Linux基金会宣布,他们将担负起Moblin社区的管理工作,而这之前,Mobli...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...