欢迎您阅读 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