多语言展示
当前在线:193今日阅读:86今日分享:14

IOS开发入门 Swift语法循环repeat-while使用

在其他语言中的while,do-while对应到Swift语法中就是while,repeat-while循环,本文就介绍Swift中的while,repeat-while使用
工具/原料

Xcode

方法/步骤
1

使用while进行最简单的循环语法如下     var i = 10     while i > 0 {         print(i)         i -= 1     }

3

while、repeat-while两者都是循环,不同之处在于,repeat-while的循环至少执行一次,while可能一次都不执行     var j = 10     repeat {        print('repeat-while: j = \(j)')        j -= 1     } while j > 10       while j > 10{        print('while: j = \(j)')     }

4

使用while遍历数组的语法如下     var arr1 = ['A', 'B', 'C']     var j = 0     while j < arr1.count{         print('while: j = \(j), arr1[j] = \(arr1[j])')         j += 1     }

5

使用while遍历集合Set通常不建议使用,最好使用for来遍历set集合     var set1 = Set(['SetA', 'SetB', 'SetC'])     var j = 0     while !set1.isEmpty {         print('j = \(j), value = \(String(describing: set1.popFirst()))')         j += 1     }

6

上述while遍历结束后,增加代码查看集合的内容,会发现,整个集合都被清空了,没有元素了     print('遍历结束后,集合长度 = \(set1.count)')

7

使用while遍历字典的语法如下     var dic1 = [0: 'Red', 1: 'Green', 2: 'Blue']     var j = 0     while j < dic1.count {         print('j = \(j), value = \(dic1[j]!)')         j += 1     }

推荐信息