Swift
- Swift语言基础教程
- 1. Swift简介
- 2. 基本语法
- 变量和常量
- 数据类型
- 字符串插值
- 数组和字典
- 3. 控制流
- 条件语句
- 循环
- 4. 函数
- 5. 类和结构体
- 6. 枚举和错误处理
- 枚举
- 错误处理
- 案例:简单的计算器
- 小项目:待办事项应用(ToDo List)
- 功能
- 代码
- 总结
Swift语言基础教程
1. Swift简介
Swift是苹果公司为iOS、macOS、watchOS和tvOS开发的一种现代编程语言。它安全、高效、并且兼具了静态和动态语言的特性。
2. 基本语法
变量和常量
- 变量使用
var
声明 - 常量使用
let
声明
swift">var myVariable = 42
myVariable = 50 // 可以更改值let myConstant = 42
// myConstant = 50 // 错误,常量无法更改
数据类型
Swift是强类型语言,支持类型推断。常见数据类型有:Int
、Double
、String
、Bool
等。
swift">let integer: Int = 42
let double: Double = 3.14
let string: String = "Hello, Swift"
let boolean: Bool = true
字符串插值
可以在字符串中插入变量和表达式。
swift">let name = "Swift"
let greeting = "Hello, \(name)!"
数组和字典
数组和字典是Swift中常用的数据结构。
swift">var array = ["Apple", "Banana", "Orange"]
array.append("Grapes")var dictionary = ["name": "John", "age": 25] as [String : Any]
dictionary["city"] = "New York"
3. 控制流
条件语句
if
语句与其他语言类似,支持else if
和else
。
swift">let score = 85if score >= 90 {print("A")
} else if score >= 80 {print("B")
} else {print("C")
}
循环
Swift支持for
、while
和repeat-while
循环。
swift">for fruit in array {print(fruit)
}var count = 3
while count > 0 {print(count)count -= 1
}repeat {print(count)count += 1
} while count < 3
4. 函数
函数使用func
关键字定义。
swift">func greet(person: String) -> String {return "Hello, \(person)!"
}let result = greet(person: "Alice")
print(result)
5. 类和结构体
Swift支持面向对象编程,类和结构体可以定义属性和方法。
swift">class Car {var brand: Stringvar year: Intinit(brand: String, year: Int) {self.brand = brandself.year = year}func drive() {print("Driving a \(year) \(brand)")}
}let myCar = Car(brand: "Toyota", year: 2020)
myCar.drive()
6. 枚举和错误处理
枚举
Swift的枚举可以包含方法,并且支持关联值。
swift">enum CompassPoint {case north, south, east, west
}let direction = CompassPoint.north
switch direction {
case .north:print("Go North")
case .south:print("Go South")
default:print("Other direction")
}
错误处理
Swift使用throw
、try
和catch
进行错误处理。
swift">enum PrinterError: Error {case outOfPapercase noToner
}func printDocument() throws {throw PrinterError.outOfPaper
}do {try printDocument()
} catch {print("Error: \(error)")
}
案例:简单的计算器
我们将实现一个简单的控制台计算器,可以处理加法、减法、乘法和除法。
swift">import Foundationfunc add(_ a: Double, _ b: Double) -> Double {return a + b
}func subtract(_ a: Double, _ b: Double) -> Double {return a - b
}func multiply(_ a: Double, _ b: Double) -> Double {return a * b
}func divide(_ a: Double, _ b: Double) throws -> Double {guard b != 0 else {throw NSError(domain: "com.calculator", code: 1, userInfo: [NSLocalizedDescriptionKey: "Cannot divide by zero"])}return a / b
}print("Enter first number: ", terminator: "")
let firstNumber = Double(readLine()!)!print("Enter second number: ", terminator: "")
let secondNumber = Double(readLine()!)!print("Choose an operation (+, -, *, /): ", terminator: "")
let operation = readLine()!var result: Double?switch operation {
case "+":result = add(firstNumber, secondNumber)
case "-":result = subtract(firstNumber, secondNumber)
case "*":result = multiply(firstNumber, secondNumber)
case "/":do {result = try divide(firstNumber, secondNumber)} catch {print(error.localizedDescription)}
default:print("Invalid operation")
}if let result = result {print("Result: \(result)")
}
小项目:待办事项应用(ToDo List)
这个小项目是一个简单的命令行版待办事项应用,支持添加、删除、列出任务。
功能
- 添加任务
- 删除任务
- 列出任务
代码
swift">import Foundationstruct Task {let id: Intvar description: Stringvar isCompleted: Bool
}class ToDoList {private var tasks: [Task] = []private var nextId: Int = 1func addTask(description: String) {let task = Task(id: nextId, description: description, isCompleted: false)tasks.append(task)nextId += 1print("Task added: \(task.description)")}func deleteTask(id: Int) {if let index = tasks.firstIndex(where: { $0.id == id }) {tasks.remove(at: index)print("Task deleted.")} else {print("Task not found.")}}func listTasks() {if tasks.isEmpty {print("No tasks.")} else {for task in tasks {print("\(task.id). [\(task.isCompleted ? "x" : " ")] \(task.description)")}}}func markTaskAsCompleted(id: Int) {if let index = tasks.firstIndex(where: { $0.id == id }) {tasks[index].isCompleted = trueprint("Task marked as completed.")} else {print("Task not found.")}}
}let toDoList = ToDoList()func showMenu() {print("""1. Add Task2. Delete Task3. List Tasks4. Mark Task as Completed5. Exit""")
}var shouldContinue = truewhile shouldContinue {showMenu()print("Choose an option: ", terminator: "")if let choice = Int(readLine()!) {switch choice {case 1:print("Enter task description: ", terminator: "")let description = readLine()!toDoList.addTask(description: description)case 2:print("Enter task ID to delete: ", terminator: "")if let id = Int(readLine()!) {toDoList.deleteTask(id: id)}case 3:toDoList.listTasks()case 4:print("Enter task ID to mark as completed: ", terminator: "")if let id = Int(readLine()!) {toDoList.markTaskAsCompleted(id: id)}case 5:shouldContinue = falsedefault:print("Invalid choice")}}
}
总结
通过这个教程和项目,你可以掌握Swift语言的基础,学会使用基本的数据类型、控制流、函数、类和错误处理,并能开发出简单的命令行应用。