SwiftUI中的数组使用
数组声明
Swift中声明和初始化数组的几种方式。
- Name
基本语法
- Type
- array-syntax
- Description
- var array: [Type] = []
- var array = Type
- var array = [element1, element2]
- Array(repeating:count:)
- Name
数组类型
- Type
- array-types
- Description
- 基本类型数组
- 对象数组
- 可选类型数组
- 多维数组
数组声明示例
// 不同的数组声明方式
var numbers: [Int] = []
var fruits = ["苹果", "香蕉", "橙子"]
var zeros = Array(repeating: 0, count: 3)
// 自定义类型数组
struct Item: Identifiable {
let id = UUID()
var name: String
}
var items = [
Item(name: "项目1"),
Item(name: "项目2")
]
列表渲染
使用ForEach和List渲染数组内容。
- Name
渲染方式
- Type
- rendering
- Description
- ForEach遍历
- List容器
- id标识
- 动态内容
- Name
常见用法
- Type
- usage
- Description
- 简单列表
- 自定义样式
- 分组列表
- 可选操作
列表渲染示例
struct ListView: View {
let fruits = ["苹果", "香蕉", "橙子", "葡萄"]
var body: some View {
List {
ForEach(fruits, id: \.self) { fruit in
Text(fruit)
}
}
// 使用ForEach直接渲染
VStack {
ForEach(0..<fruits.count, id: \.self) { index in
Text("\(index + 1). \(fruits[index])")
}
}
}
}
数组操作
常见的数组操作方法。
- Name
基础操作
- Type
- basic-operations
- Description
- 添加元素(append)
- 删除元素(remove)
- 插入元素(insert)
- 更新元素
- Name
高级操作
- Type
- advanced-operations
- Description
- 数组排序(sort)
- 数组过滤(filter)
- 数组映射(map)
- 数组归约(reduce)
数组操作示例
struct ArrayOperationsView: View {
@State private var numbers = [1, 2, 3, 4, 5]
var body: some View {
VStack {
// 显示原始数组
Text("原始数组: \(numbers.map{String($0)}.joined(separator: ", "))")
Button("添加数字") {
numbers.append(6)
}
Button("删除最后一个") {
numbers.removeLast()
}
// 显示偶数
let evenNumbers = numbers.filter { $0 % 2 == 0 }
Text("偶数: \(evenNumbers.map{String($0)}.joined(separator: ", "))")
// 所有数字乘2
let doubled = numbers.map { $0 * 2 }
Text("乘2: \(doubled.map{String($0)}.joined(separator: ", "))")
}
}
}
实用技巧
数组使用的最佳实践。
- Name
性能优化
- Type
- optimization
- Description
- 预分配容量
- 避免频繁修改
- 使用lazy操作
- 合理使用索引
- Name
常见陷阱
- Type
- pitfalls
- Description
- 索引越界
- 可选值处理
- 值类型特性
- 内存管理
最佳实践示例
struct TodoList: View {
@State private var todos = [
"学习Swift",
"练习SwiftUI",
"完成项目"
]
@State private var newTodo = ""
var body: some View {
VStack {
List {
ForEach(todos.indices, id: \.self) { index in
Text(todos[index])
}
.onDelete(perform: deleteTodo)
}
HStack {
TextField("新任务", text: $newTodo)
Button("添加") {
if !newTodo.isEmpty {
todos.append(newTodo)
newTodo = ""
}
}
}
.padding()
}
}
func deleteTodo(at offsets: IndexSet) {
todos.remove(atOffsets: offsets)
}
}