1. Dạng x...y
Code mẫu:
for i in 0...2 {
print("Index:", i)
}
//Result:
Index: 0
Index: 1
Index: 2
2. Dạng x..<y
Code mẫu:
for i in 0..<2 {
print("Index:", i)
}
//Result:
Index: 0
Index: 1
3. Dạng Array
Code mẫu:
let names = ["Le", "Tuan", "Leo", "Hulk"]
for name in names {
print("Name: ", name)
}
//Result:
Name: Le
Name: Tuan
Name: Leo
Name: Hulk
4. Dạng Array[index...]
Code mẫu:
let names = ["Le", "Tuan", "Leo", "Hulk"]
for name in names[2...] {
print("Name:", name)
}
//Result:
Name: Leo
Name: Hulk
5. Dạng Array[...index]
Code mẫu:
let names = ["Le", "Tuan", "Leo", "Hulk"]
for name in names[...2] {
print("Name:", name)
}
//Result:
Name: Le
Name: Tuan
Name: Leo
6. Dạng Array[..<index]
Code mẫu:
let names = ["Le", "Tuan", "Leo", "Hulk"]
for name in names[..<2] {
print("Name:", name)
}
//Result:
Name: Le
Name: Tuan
7. Dạng stride
stride có quy tắc như sau: là 1 list [fromValue + (0 -> toValue) * stride] ==> fromValue + (0 * stride) , fromValue + 1 * stride, ... fromValue + toValue * stride phần tử cuối có giá trị không lớn hơn toValue nếu stride là dương và ngược lại phần tử cuối sẽ không nhỏ hơn toValue
Code mẫu:
//dương
for i in stride(from: 1, to: 10, by: 2) {
print(i)
}
//Result:
1
3
5
7
9
//-----------
//âm
for i in stride(from: 10, to: 1, by: -2) {
print(i)
}
//Result:
10
8
6
4
2
8. Dạng '_'
Code mẫu:
for _ in 1...3 {
print("Hello World")
}
//Result:
Hello World
Hello World
Hello World
9. [Bonus] Dạng Array.forEach
Code mẫu:
let names = ["Le", "Tuan", "Leo", "Hulk"]
names.forEach { name in
print("Name:", name)
}
//Result:
Name: Le
Name: Tuan
Name: Leo
Name: Hulk
nguồn : https://viblo.asia/p/tong-hop-cac-cu-phap-lenh-for-thuong-gap-trong-swift-3-tro-di-1Je5E8AGlnL
Không có nhận xét nào:
Đăng nhận xét