swift中数组和字符串操作

数组操作

1.以下例子使用 for-in 遍历一个数组所有元素
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
2.可以通过遍历一个字典来访问它的键值对
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
// cats have 4 legs
// ants have 6 legs
// spiders have 8 legs
3.for-in 循环还可以使用数字范围
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
4.如果你不需要区间序列内每一项的值,你可以使用下划线(_)替代变量名来忽略这个
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// 输出“3 to the power of 10 is 59049”
5.创建一个带有默认值的数组
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]
6.利用下标来一次改变一系列数据值,即使新数据和原有数据的数量是不一样的。
shoppingList[4...6] = ["Bananas", "Apples"]

7.数组的 insert(_:at:) 方法在某个指定索引值之前添加数据项
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList 现在有7项
// 现在是这个列表中的第一项是“Maple Syrup”
8.数组使用 remove(at:) 方法来移除数组中的某一项
let mapleSyrup = shoppingList.remove(at: 0)
// 索引值为0的数据项被移除
9.把数组中的最后一项移除
let apples = shoppingList.removeLast()
// 数组的最后一项被移除了
10.把数组中的数据反转
let apples = shoppingList.reversed()
// 数组里面的数据 1,2,3 变成 3,2,1
11.数组遍历
 //遍历数组
    for (index, model) in iosArray.enumerated() {
        print("\(index): \(model)")
    }
12.数组遍历
 //遍历数组
    for index in dataArray.indices {
        print("\(index): \(model)")
    }
13.选取数组中的前几个数据
 //数组中前几个数据
    var combine = ["1", "2", "3", "4", "5"]
     combine = Array(combine.prefix(3))
        for model in combine {
            print(model)
        }
14.删除模型数组中,特定的模型
 //删除模型数组中,特定的模型
    eventListArray.removeAll(where: {$0.eventId == firstModel.eventId})

字符串操作

1.截取前几位字符
let string = "abcd1234.pdf"
let prefix = string.prefix(3)
print(prefix)
//打印结果:abc
2.截取后几位字符
let string = "abcdef1234.pdf"
let suffix = string.suffix(3)
print(suffix)
//打印结果:pdf
3.去掉前几位字符
let string = "abcdef1234.pdf"
let dropfirst = string.dropFirst(3)
print(dropfirst)
//打印结果:def1234.pdf
4.去掉后几位字符
let string = "abcdef1234.pdf"
let dropLast = string.dropLast(4)
print(dropLast)
//打印结果:abcdef1234
5.截取字符串中间的字符
let string = "abcdef1234.pdf"
let numStr = string.dropFirst(6).prefix(4)
print(numStr)
//或者
if let index1 = string.lastIndex(of: "1"),
   let index2 = string.lastIndex(of: "4") {
    let num = String(string[index1...index2])
    print(num)
}
//打印结果:1234

你可能感兴趣的:(swift中数组和字符串操作)