Swift 基本语法
Swift 是一种由苹果公司开发的编程语言,用于在 iOS、macOS、watchOS 和 tvOS 上开发应用程序。它是一种强类型语言,具有清晰的语法和现代特性,使得开发过程更加高效和易于维护。本文将介绍 Swift 的一些基本语法,帮助初学者快速上手。
变量和常量
在 Swift 中,使用 let
关键字来声明一个常量,使用 var
关键字来声明一个变量。常量的值在初始化后不能被改变,而变量的值可以随时更改。
let constant = "Hello, Swift!"
var variable = "Hello, World!"
variable = "Hello, Swift!"
数据类型
Swift 提供了多种内置数据类型,包括整数(Int)、浮点数(Double、Float)、布尔值(Bool)和字符串(String)等。
let integer: Int = 42
let double: Double = 3.14
let boolean: Bool = true
let string: String = "Swift"
控制流
Swift 提供了多种控制流语句,包括 if
、for-in
、while
和 switch
等。
if boolean {print("True")
} else {print("False")
}for index in 1...5 {print(index)
}var i = 1
while i <= 5 {print(i)i += 1
}let number = 3
switch number {
case 1:print("One")
case 2:print("Two")
case 3:print("Three")
default:print("Other")
}
函数
在 Swift 中,使用 func
关键字来定义一个函数。函数可以接受参数并返回值。
func greet(person: String) -> String {return "Hello, \(person)!"
}
print(greet(person: "Swift"))
闭包
闭包是一种自包含的函数代码块,可以在代码中被传递和使用。闭包类似于其他编程语言中的匿名函数或 lambda 表达式。
let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { $0 * $0 }
print(squaredNumbers)
类和结构体
Swift 支持面向对象编程,使用 class
关键字来定义一个类,使用 struct
关键字来定义一个结构体。类和结构体都可以定义属性和方法。
class Person {var name: Stringinit(name: String) {self.name = name}func greet() {print("Hello, \(name)!")}
}struct Point {var x: Intvar y: Intfunc moveBy(x deltaX: Int, y deltaY: Int) {x += deltaXy += deltaY}
}
枚举和协议
Swift 使用 enum
关键字来定义一个枚举,使用 protocol
关键字来定义一个协议。枚举可以包含方法,协议用于定义一组规则,供类、结构体或枚举遵循。
enum Direction {case north, south, east, westfunc opposite() -> Direction {switch self {case .north:return .southcase .south:return .northcase .east:return .westcase .west:return .east}}
}protocol Vehicle {var numberOfWheels: Int { get }func drive()
}class Car: Vehicle {var numberOfWheels: Int = 4func drive() {print("Driving a car with \(numberOfWheels) wheels")}
}
错误处理
Swift 提供了错误处理机制,使用 throws
关键字来标记一个可以抛出错误的函数,使用 try
关键字来调用可能抛出错误的函数。
enum FileError: Error {case fileNotFound, unreadable, encodingFailed
}func readFile(atPath path: String) throws -> String {guard fileExists(atPath: path) else {throw FileError.fileNotFound}guard isReadable(atPath: path) else {throw FileError.unreadable}let contents = try String(contentsOfFile: path, encoding: .utf8)return contents
}do {let contents = try readFile(atPath: "example.txt")print(contents)
} catch FileError.fileNotFound {print("File not found")
} catch FileError.unreadable {print("File is unreadable")
} catch {print("