for 循环
示例:
for i in 0...10{
print(i)
}
// 通过 _ 忽略遍历的值,可以没有变量,用_代替
for _ in 0...10{
print("tes")
}
数组遍历
//遍历数组
var names = ["name0","name1","name2","name3"]
for name in names{
print(name)
}
// 有时遍历数组的时候,需要知道是第几个元素,通过这个方法 names.enumerated 将数组变成元组,然后通过一个匿名元组来接收,元组可以将索引和元素一一对应起来
for (index,name)in names.enumerated(){
print("\(index) : \(name)")
}
字符串遍历
// 字符串的遍历
// 获取到一个字符串的所有字符
let name = "wangxiao"
//遍历一
for c in "wangxiao".characters{
print(c)
}
//遍历二
for c in name.characters{
print(c)
}
// 变量或者字符串都行
字典的遍历
// 字典是无序的,所以没办法拿到索引
let person = ["name":"zhangsan","age":"19","gender":"man"]
for d in person{
print(d)
}
for d in person{
print(d.key)
print(d.value)
print("\(d.key)"+":"+"\(d.value)")
print("\(d.key)"+"\(d.value)")
}
// 通过一个匿名元组来接收结果
var count = 0
for (key,value ) in person {
print("\(key) : \(value)",count )
count += 1
}
原文链接:https://www.f2er.com/swift/322664.html