You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You use the for-in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string.
letnames=["Anna","Alex","Brian","Jack"]
for name in names {print("Hello, \(name)!")}// Hello, Anna!// Hello, Alex!// Hello, Brian!// Hello, Jack!
You can also iterate over a dictionary to access its key-value pairs. Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated, and you can decompose the (key, value) tuple’s members as explicitly named constants for use within the body of the for-in loop.
Dictionary are inherently unordered
letnumberOfLegs=["spider":8,"ant":6,"cat":4]
for (animalName, legCount) in numberOfLegs {print("\(animalName)s have \(legCount) legs")}// ants have 6 legs// spiders have 8 legs// cats have 4 legs
You can also use for-in loops with numeric ranges. This example prints the first few entries in a five-times table:
for index in 1...5{print("\(index) times 5 is \(index *5)")}// 1 times 5 is 5// 2 times 5 is 10// 3 times 5 is 15// 4 times 5 is 20// 5 times 5 is 25
If you don’t need each value from a sequence, you can ignore the values by using an underscore in place of a variable name
letbase=3letpower=10varanswer=1
for _ in 1...power {
answer *= base
}print("\(base) to the power of \(power) is \(answer)")// Prints "3 to the power of 10 is 59049"
use stride(from:to:by:) to determinate loop step
letminutes=60letminuteInterval=5
for tickMark in stride(from:0, to: minutes, by: minuteInterval){// render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)print(tickMark)}
The text was updated successfully, but these errors were encountered:
waltcow
changed the title
swift4 语法备忘
swift4 语法备忘- control flow
Apr 15, 2018
waltcow
changed the title
swift4 语法备忘- control flow
swift4 语法备忘- Control Flow
Apr 17, 2018
For-In Loops
Dictionary are inherently unordered
The text was updated successfully, but these errors were encountered: