별 내용 아니지만 몰랐던 방식이라 적어두기 :)
for index in 0..<numbers.count {
print(numbers[index])
}
for (index, element) in numbers.enumerated() {
print(element)
}
numbers.forEach { num in
print(num)
}
어떤 배열을 순회하는 방식에는 여러가지가 있다
위에 적혀있는 방식 말고도 또 다른 방식들도 있는데 주로 사용하는 방식은 위와 같다.
배열을 순회하면서 그 index에 맞는 처리를 해줄 때는 가장 위의 것을 사용하곤 하는데
indices라는 property를 사용하면 조금 더 깔끔하게 작성할 수 있다 !
+ forEach문과도 사용할 수 있음
for index in numbers.indices {
print(numbers[index])
}
numbers.indices.forEach {
print(numbers[$0])
}
'iOS > swift' 카테고리의 다른 글
[swift] @discardableResult 키워드 (0) | 2022.04.16 |
---|---|
[Swift] if let 과 guard let (0) | 2022.02.20 |
[Swift] class / struct - initializer - 조금 더 편하게 작성하는 법 (0) | 2022.01.21 |