This time, I learned about for-in statements, so I will output them.
*** The for-in statement iterates as many times as there are elements, passing each element to the executable statement in sequence. *** ***
The basic writing method is as follows
qiita.rbvar
for element name in sequence{
Statements that are repeatedly executed element by element
}
Let's look at a simple example next.
qiita.rbvar
1.let array = [1,2,3]
2.for element in array {
print(element)
}
Execution result
1
2
3
In the above example, the values in the array array are accessed one by one through the constant element.
When enumerating elements of Dictionary <key, Value> type with for-in, the element type is a tuple of type (key, value). For example, a value of type [String: Int] When passed to a for-in statement, the element will be of type (String: Int).
Let's look at a simple example.
qiita.rbvar
let dictionary = ["a": 1,"b": 2]
for (key,value) in dictionary {
print("key:\(key),Value\(value)")
}
Execution result
key: a Value: 1
key: b Value: 2
The break statement breaks the execution statement and ends the entire repeating statement. For example, it is used when you need to repeat it any more.
Let's look at a simple example.
qiita.rbvar
var containsThree = false
let array = [1,2,3,4,5]
for element in array {
if element == 3 {
containsThree = true
break
//Finish when 3 is found
}
print("element:\(containsTwo)")
}
print("containsTwo: \(containsTwo)")
Execution result
element: 3
containsTwo: true
In the above example, it is a program that checks if the array contains 3. Since it is not necessary to repeat the following when 3 is found, the break statement is used to end the repeating statement.
The continue statement suspends the execution statement and then continues the subsequent iterations. For example, it is used to skip processing only in specific cases.
qiita.rbvar
var adds = [Int]()
let array = [1,2,3,]
for element in array {
if element % 2 == 1 {
adds.append(element)
continue
}
print("even: \(element)")
}
print("odds:\(adds)")
Execution result
even: 2
adds: [1,3]
In the above example, unlike the break statement, the subsequent iterations are continued, and you can see that all the elements are processed.
Recommended Posts