Swift基本语法(1/3)

97 阅读4分钟

1. 变量和常量

  • 变量 是可以改变的值。在 Swift 中使用 var 关键字声明变量。
  • 常量 是一旦设定就不可更改的值。使用 let 关键字声明常量。
var variable = "I can change" 
variable = "I have changed" 
let constant = "I cannot change" 
// constant = "This will cause an error" // 错误:常量不能被改变

2. 基本数据类型

Swift 提供了多种基本数据类型,包括整数(Int)、浮点数(Double 和 Float)、布尔值(Bool)和字符串(String)。

let integer: Int = 100 
let double: Double = 10.5 
let boolean: Bool = true 
let string: String = "Hello, Swift!"

3. 集合类型

Swift 提供了三种主要的集合类型:ArraySetDictionary

  • 数组(Array)是有序的值的集合。
  • 集合(Set)是无序且唯一的值的集合。
  • 字典(Dictionary)是无序的键值对的集合。
var array: [Int= [123var setSet<String= Set(["apple""orange""banana"])
var dictionary: [StringInt= ["apple"1"orange"2]

4. 控制流

Swift 中的控制流指令用于根据不同条件执行不同的代码路径。主要包括条件语句、循环以及控制转移语句。

条件语句

  • ifelse 用于基于特定条件执行代码。
  • guard 用于提早退出一个代码块,通常用于提高代码可读性。
let score = 85

if score > 90 {
    print("优秀")
} else if score > 60 {
    print("及格")
} else {
    print("不及格")
}

func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }
    print("Hello, \(name)!")
}

循环

  • for-in 循环用于遍历一个序列,如数组或者数值范围。
  • while 循环在条件为真时重复执行代码块。
  • repeat-while 循环至少执行一次代码块,然后再检查条件。
for number in 1...5 {
    print(number)
}

var countDown = 5
while countDown > 0 {
    print(countDown)
    countDown -= 1
}

repeat {
    print("这行代码至少执行一次")
} while countDown > 0

控制转移语句

  • break 用于立即结束整个控制流的执行。
  • continue 用于结束当前循环迭代,立即开始下一次迭代。
for number in 1...10 {
    if number % 2 == 0 {
        continue
    }
    if number > 5 {
        break
    }
    print(number) // 打印 1, 3, 5
}

5. 函数

函数是执行特定任务的代码块。Swift 的函数具有灵活的参数和返回值类型。

基本函数

func greet(name: String) -> String {
    return "Hello, \(name)!"
}

函数参数

  • 参数可以有默认值。
  • 可以传递可变数量的参数(用 ... 表示)。
func greet(person: String, nicely: Bool = true) {
    if nicely {
        print("Hello, \(person)!")
    } else {
        print("Oh no, it's \(person) again...")
    }
}

greet(person: "Jane")         // 使用默认参数
greet(person: "Jane", nicely: false)

返回多个值

使用元组来从函数返回多个值。

func minMax(array: [Int]) -> (min: Int, max: Int)? {
    guard let min = array.min(), let max = array.max() else {
        return nil
    }
    return (min, max)
}

6. 闭包

闭包是自包含的功能代码块,可以在代码中被传递和调用。

基本闭包

let sayHello = { (name: String) in
    print("Hello, \(name)")
}
sayHello("Swift")

捕获值

闭包可以从创建它们的上下文中捕获常量或变量。

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    let incrementer: () -> Int = {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}

let incrementByTwo = makeIncrementer(forIncrement: 2)
incrementByTwo() // 返回 2
incrementByTwo() // 返回 4

尾随闭包

当函数的最后一个参数是闭包时,可以使用尾随闭包的语法。

func performOperation(on numbers: [Int], using closure: (Int) -> Int) {
    for number in numbers {
        let result = closure(number)
        print(result)
    }
}

performOperation(on: [1, 2, 3]) { number in
    return number

7. 枚举

枚举定义了一个通用类型的一组相关值,并使你可以在代码中以类型安全的方式来使用这些值。

基础枚举

枚举可以定义一个通用类型的一组相关命名值,使你的代码更具可读性和安全性。

enum CompassPoint {
    case north
    case south
    case east
    case west
}

var direction = CompassPoint.west
direction = .east // 当类型已知时,可以这样简写

关联值

枚举的每个成员可以有一个或多个与之相关联的值,这些值可以是不同的类型。

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")

原始值

枚举成员可以使用相同类型的默认值预先填充(称为原始值)。

enum ASCIIControlCharacter: Character {
    case tab = "\t"
    case lineFeed = "\n"
    case carriageReturn = "\r"
}

let tabCharacter = ASCIIControlCharacter.tab.rawValue

递归枚举

递归枚举是一种枚举类型,它有一个或多个枚举成员的关联值是枚举类型本身。

enum ArithmeticExpression {
    case number(Int)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}

let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))

使用 Switch 语句匹配枚举值

使用 switch 语句来匹配枚举值是一种常见的做法。

switch direction {
case .north:
    print("Lots of planets have a north")
case .south:
    print("Watch out for penguins")
case .east:
    print("Where the sun rises")
case .west:
    print("Where the skies are blue")
}

枚举迭代

Swift 4.2 引入了一种新的协议 CaseIterable,它可以让枚举类型自动提供一个包含所有枚举案例的集合。

enum Beverage: CaseIterable {
    case coffee, tea, juice
}

let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) beverages available")

for beverage in Beverage.allCases {
    print(beverage)
}