도래울

swift for in loop 본문

개발/iOS

swift for in loop

도래울 2016. 7. 13. 09:03

For-In Loops

You use the for-in loop to iterate over a sequence, such as ranges of numbers, items in an array, or characters in a string.

This example prints the first few entries in the five-times table:

  1. for index in 1...5 {
  2. print("\(index) times 5 is \(index * 5)")
  3. }
  4. // 1 times 5 is 5
  5. // 2 times 5 is 10
  6. // 3 times 5 is 15
  7. // 4 times 5 is 20
  8. // 5 times 5 is 25

The sequence being iterated over is a range of numbers from 1 to 5, inclusive, as indicated by the use of the closed range operator (...). The value of index is set to the first number in the range (1), and the statements inside the loop are executed. In this case, the loop contains only one statement, which prints an entry from the five-times table for the current value of index. After the statement is executed, the value of index is updated to contain the second value in the range (2), and the print(_:separator:terminator:) function is called again. This process continues until the end of the range is reached.

In the example above, index is a constant whose value is automatically set at the start of each iteration of the loop. As such, index does not have to be declared before it is used. It is implicitly declared simply by its inclusion in the loop declaration, without the need for a let declaration keyword.

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.

  1. let base = 3
  2. let power = 10
  3. var answer = 1
  4. for _ in 1...power {
  5. answer *= base
  6. }
  7. print("\(base) to the power of \(power) is \(answer)")
  8. // Prints "3 to the power of 10 is 59049"

The example above calculates the value of one number to the power of another (in this case, 3 to the power of10). It multiplies a starting value of 1 (that is, 3 to the power of 0) by 3, ten times, using a closed range that starts with 1 and ends with 10. For this calculation, the individual counter values each time through the loop are unnecessary—the code simply executes the loop the correct number of times. The underscore character (_) used in place of a loop variable causes the individual values to be ignored and does not provide access to the current value during each iteration of the loop.

Use a for-in loop with an array to iterate over its items.

  1. let names = ["Anna", "Alex", "Brian", "Jack"]
  2. for name in names {
  3. print("Hello, \(name)!")
  4. }
  5. // Hello, Anna!
  6. // Hello, Alex!
  7. // Hello, Brian!
  8. // 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. Here, the dictionary’s keys are decomposed into a constant called animalName, and the dictionary’s values are decomposed into a constant called legCount.

  1. let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
  2. for (animalName, legCount) in numberOfLegs {
  3. print("\(animalName)s have \(legCount) legs")
  4. }
  5. // ants have 6 legs
  6. // cats have 4 legs
  7. // spiders have 8 legs

Items in a Dictionary may not necessarily be iterated in the same order in which they were inserted. The contents of a Dictionary are inherently unordered, and iterating over them does not guarantee the order in which they will be retrieved. For more on arrays and dictionaries, see Collection Types.


'개발 > iOS' 카테고리의 다른 글

Loop through subview to check for empty UITextField - Swift  (0) 2016.07.13
remove all subviews of a view in Swift  (0) 2016.07.13
swift uitableview checkbox example  (0) 2016.07.13
Swift string replace  (0) 2016.07.12
Swift 배열과 딕셔너리  (0) 2016.07.12
Comments