Swift 数组的相关操作示范

10 min read
  1. 创建一个数组
var fruits = ["apple", "banana", "orange", "grape", "pear"]
  1. 访问数组中的元素
print(fruits[0]) // apple
print(fruits[3]) // grape
  1. 添加新的元素到数组中
fruits.append("kiwi")
print(fruits) // ["apple", "banana", "orange", "grape", "pear", "kiwi"]
  1. 插入元素到数组中的指定位置
fruits.insert("watermelon", at: 2)
print(fruits) // ["apple", "banana", "watermelon", "orange", "grape", "pear", "kiwi"]
  1. 删除数组中指定位置的元素
fruits.remove(at: 3)
print(fruits) // ["apple", "banana", "watermelon", "grape", "pear", "kiwi"]
  1. 修改数组中的元素
fruits[1] = "cherry"
print(fruits) // ["apple", "cherry", "watermelon", "grape", "pear", "kiwi"]
  1. 数组长度
print(fruits.count) // 6
  1. 遍历数组中的所有元素
for fruit in fruits {
    print(fruit)
}

// 输出:
// apple
// cherry
// watermelon
// grape
// pear
// kiwi
  1. 判断数组是否为空
if fruits.isEmpty {
    print("The array is empty.")
} else {
    print("The array has \(fruits.count) elements.")
}
  1. 按照字母顺序排序数组
fruits.sort()
print(fruits) // ["apple", "cherry", "grape", "kiwi", "pear", "watermelon"]