Playground-noun:a place where people can playimport UIKit//------------------------------------------------------------------------------1. ForThe traditional for loop approach is also supported in Swiftvar num =0Forvar i =0; I <10; i++) {num + = I}num//------------------------------------------------------------------------------2. For-in is used to traverse an interval (range), sequence (sequence), collection (collection), Series (progression)All elements execute a series of statements1> closed interval cycle, from 1 cycles to 10num =0For IInch1...10 {num + = I}num2> open interval cycle, from 1 cycles to 9num =0For IInch1..<10 {num + = I}num3> If you do not need to know the value of each item within the interval, you can use an underscore (_) to override the variable name, ignoring the access to the interval value num =0For _Inch1...10 {Num++}numnum =0For IInch0...5 { For JInch0...5 { num = i + j}}num//------------------------------------------------------------------------------3. Loop-generated Arrayvar array = [String] ()For IInch0..<10 {Array.append ("Itcast \ (i)")}array//------------------------------------------------------------------------------4. Iterate through a dictionaryvar agedict:dictionary<string, int> = ["Mary":19,"Rose":20]var names = [String] ()var ages = [Int] ()For (Key,ValueIn Agedict {Names.append (Key)Ages.append (Value)}namesagesvar keys = [String] ()var values = [String] ()var dict1 = ["Name":"Mike,""Age":"18"];For (name, age)In Dict1 {Keys.append (name)Values.append (age)}keysvalues//------------------------------------------------------------------------------5. Use tags to exit loops//the use of the label 1 of the function is: you can explicitly specify which loop to exit, the following example is to exit the loop named "Mainloop" var result = Span class= "number" >1;mainloop: for i in 1...5 { for j in 1...5 { result + = J if (i = = 3 & & j = = 3) { break mainloop }}}result
Swift basic usage-for loops, iterates through dictionaries, loops through arrays