Swift语言基础教程、Swift练手小项目、Swift知识点实例化学习

Swift

Swift语言基础教程

1. Swift简介

Swift是苹果公司为iOS、macOS、watchOS和tvOS开发的一种现代编程语言。它安全、高效、并且兼具了静态和动态语言的特性。

2. 基本语法

变量和常量

  • 变量使用var声明
  • 常量使用let声明
swift 复制代码
var myVariable = 42
myVariable = 50 // 可以更改值

let myConstant = 42
// myConstant = 50 // 错误,常量无法更改

数据类型

Swift是强类型语言,支持类型推断。常见数据类型有:IntDoubleStringBool等。

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 ifelse

swift 复制代码
let score = 85

if score >= 90 {
    print("A")
} else if score >= 80 {
    print("B")
} else {
    print("C")
}

循环

Swift支持forwhilerepeat-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: String
    var year: Int
    
    init(brand: String, year: Int) {
        self.brand = brand
        self.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使用throwtrycatch进行错误处理。

swift 复制代码
enum PrinterError: Error {
    case outOfPaper
    case noToner
}

func printDocument() throws {
    throw PrinterError.outOfPaper
}

do {
    try printDocument()
} catch {
    print("Error: \(error)")
}

案例:简单的计算器

我们将实现一个简单的控制台计算器,可以处理加法、减法、乘法和除法。

swift 复制代码
import Foundation

func 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)

这个小项目是一个简单的命令行版待办事项应用,支持添加、删除、列出任务。

功能

  1. 添加任务
  2. 删除任务
  3. 列出任务

代码

swift 复制代码
import Foundation

struct Task {
    let id: Int
    var description: String
    var isCompleted: Bool
}

class ToDoList {
    private var tasks: [Task] = []
    private var nextId: Int = 1
    
    func addTask(description: String) {
        let task = Task(id: nextId, description: description, isCompleted: false)
        tasks.append(task)
        nextId += 1
        print("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 = true
            print("Task marked as completed.")
        } else {
            print("Task not found.")
        }
    }
}

let toDoList = ToDoList()

func showMenu() {
    print("""
    1. Add Task
    2. Delete Task
    3. List Tasks
    4. Mark Task as Completed
    5. Exit
    """)
}

var shouldContinue = true

while 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 = false
        default:
            print("Invalid choice")
        }
    }
}

总结

通过这个教程和项目,你可以掌握Swift语言的基础,学会使用基本的数据类型、控制流、函数、类和错误处理,并能开发出简单的命令行应用。

相关推荐
o独酌o23 分钟前
递归的‘浅’理解
java·开发语言
Book_熬夜!26 分钟前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
m0_631270401 小时前
高级c语言(五)
c语言·开发语言
2401_858286111 小时前
53.【C语言】 字符函数和字符串函数(strcmp函数)
c语言·开发语言
程序猿练习生2 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
2401_858120262 小时前
MATLAB中的无线通信系统部署和优化工具有哪些
开发语言·matlab
MATLAB滤波2 小时前
【PSINS】基于PSINS工具箱的EKF+UKF对比程序|三维定位|组合导航|MATLAB
开发语言·matlab
2401_858120532 小时前
MATLAB在嵌入式系统设计中的最佳实践
开发语言·matlab
蓝裕安2 小时前
伪工厂模式制造敌人
开发语言·unity·游戏引擎
无名之逆2 小时前
云原生(Cloud Native)
开发语言·c++·算法·云原生·面试·职场和发展·大学期末