본문 바로가기
모바일앱/Swift

Day04 For_Loops

by GeekCode 2021. 11. 29.
반응형

For 반복문은 for each와 거의 같다

 

레인지를 활용하는 방법 익히기

📌이상 이하

0...5

 

📌이상 미만

0..<5

 

 

📌index 혹은 iterate

// i-> index 혹은 iterate 때문에 i로 쓰는게 일반적 ->  i를 나중에 다시 쓰지않는다고 알림창이 뜨기때문에 _로 대체사용가능

 

📌where 이후는 반복을 위한 조건을 사용할 수 있음

짝수일때

//for index in 0..<5 where index % 2 == 0 {

}

 

📌for loops 안에 다시 for loops 를 넣을 수 있음

for _ in 0..<24 {

    let randomNumber = Int.random(in: 0...100)

    randomInts.append(randomNumber)

}

 

import UIKit


// #1 레인지(범위) 이상 이하
// 0...5
// 0,1,2,3,4,5  총 6자리


// #2 이상 미만
//0..<5
//0,1,2,3,4

// i-> index 혹은 iterate 때문에 i로 쓰는게 일반적
//for index in 0...5 {
// print("index: \(index)")
//}

/*
 index: 0
 index: 1
 index: 2
 index: 3
 index: 4
 index: 5
 */

//for index in 0..<5 {
// print("index: \(index)")
//}
/*
 index: 0
 index: 1
 index: 2
 index: 3
 index: 4
 */

//#4 index에서 짝수만 구하기
//for index in 0..<5 where index % 2 == 0 {
// print("짝수: \(index)")
//}
/*
 짝수: 0
 짝수: 2
 짝수: 4
 */

//#5 빈 배열생성하기
//var randomInts: [Int] = []
var randomInts: [Int] = [Int]()

for _ in 0..<24 {
    let randomNumber = Int.random(in: 0...100)
    randomInts.append(randomNumber)
}

print("randomInt: \(randomInts)")
//-> randomInt: [21, 12, 11, 83, 49, 53, 75, 93, 38, 94, 78, 62, 0, 32, 18, 70, 88, 24, 42, 81, 22, 35, 18, 49]

 

반응형

'모바일앱 > Swift' 카테고리의 다른 글

Day08 function parameter  (0) 2021.12.03
Day07 property_observer  (0) 2021.12.02
Day06 class_struct  (0) 2021.11.30
Day05 Unwrap_Optional  (0) 2021.11.29
Day03: enum  (0) 2021.11.29
Day02 : For-each(자료 보강 필요)  (0) 2021.11.28
Day01 : Conditional Statements_If  (0) 2021.11.26
생성자 이해하기, 2-phase Initialization, Convenience Initializer  (0) 2021.10.20