Blog
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)

HiuZing

🍑
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)
  • Swift入门
    • 入门
      • 常量和变量
      • 数组和字典
      • 控制流
      • 函数和闭包
  • Swift
HiuZing
2026-08-17
目录

Swift入门

# 入门

# 常量和变量

使用 let 可以创建常量,而 var 则可以创建变量。

var myVariable = 42
myVariable = 50
let myConstant = 42
1
2
3

将值包含在字符串中,括号之前加上一个反斜杠符号\

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
1
2
3
4

# 数组和字典

访问元素

var fruits = ["strawberries", "limes", "tangerines"]
fruits[1] = "grapes"

var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
 ]
occupations["Jayne"] = "Public Relations"
1
2
3
4
5
6
7
8

添加元素

fruits.append("blueberries")
print(fruits)
// Prints "["strawberries", "grapes", "tangerines", "blueberries"]".
1
2
3

编写数组或字典

对于数组,写作 [] ;而对于字典,则写作 [:] 。

fruits = []
occupations = [:]
1
2

空数组或字典赋值给一个新的变量,明确指定该变量的类型

let emptyArray: [String] = []
let emptyDictionary: [String: Float] = [:]
1
2

# 控制流

使用 if 和 switch 来构建条件语句

使用 for 至 in 、 while 以及 repeat 至 while 来构建循环语句

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)
// Prints "11".
1
2
3
4
5
6
7
8
9
10
11

接收值

let scoreDecoration = if teamScore > 10 {
    "🎉"
} else {
    ""
}
print("Score:", teamScore, scoreDecoration)
// Prints "Score: 11 🎉".
1
2
3
4
5
6
7

使用 ..< 来创建一系列索引,从而在循环中使用这些索引

var total = 0
for i in 0..<4 {
    total += i
}
print(total)
// Prints "6".
1
2
3
4
5
6

# 函数和闭包

func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
1
2
3
4

默认情况下,函数会使用其参数名称作为参数的标签。可以在参数名称之前添加自定义标签,或者写入 _ 以不使用任何参数标签。

使用元组来创建复合值

从函数中返回多个值。元组的元素可以通过名称或序号来访问

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0


    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }


    return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
// Prints "120".
print(statistics.2)
// Prints "120".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

嵌套函数

func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()
1
2
3
4
5
6
7
8
9

作为返回值返回

func makeIncrementer() -> ((Int) -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()
increment(7)
1
2
3
4
5
6
7
8

作为参数使用

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)
1
2
3
4
5
6
7
8
9
10
11
12
13

闭包

上次更新: 2026/08/17, 09:31:50
最近更新
01
基础知识
08-14
02
Kotlin入门
08-14
03
面向对象
08-12
更多文章>
Theme by Vdoing | Copyright © 2021-2026 WeiXiaojing | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式