Swift 循环(for ,while, do..while)

Swift 循环(for ,while, do..while)_第1张图片
Swift.png

for循环

  • 常见的写法
//传统的写法,已经在Swift 3中移除了额,这种写法是错误的

//for var i = 0; i < 10; i += 1 {
//    
//    print(i);
//}

//在swift中 for循环 要使用区间,之前的写法不在适用了
//正确的写法
for i in 0..<10 {
    print(i);
}

// _代表忽略的意思  区间遍历
for _ in 0..<10 {
    print("zaza");
}



var numbers = ["cc","ss","dd"]

for i in 0 ..< numbers.count {
   print(numbers[i]);
}


//反向遍历 
 let testArray = ["1","2","3","4"];
        
        for i in testArray.reversed() {
            
            print(i)
        }

//打印结果: 4,3,2,1


while循环

var i = 10;
//条件必须为真才执行
while i > 0 {
    i -= 1;
    print(i);
}

repeat...while循环 代替 do..while

  • 注意 在swift中 do..while循环已经被 repeat...while 代替,原因:do在swift有特殊的含义


    do..while.jpg
var i = 5;

repeat{
    i += 1;
    print(i);

} while i < 10



你可能感兴趣的:(Swift 循环(for ,while, do..while))