๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐ŸŽ iOS/Swift

[Swift] ์Šค์œ„ํ”„ํŠธ ๋ฐ˜๋ณต๋ฌธ(Loops, Repetitive Statement)

์Šค์œ„ํ”„ํŠธ ๋ฐ˜๋ณต๋ฌธ(Loops, Repetitive Statement)

  • for๋ฌธ
  • while๋ฌธ

๐ŸŽ  for๋ฌธ

  • ์ผ์ • ํšŸ์ˆ˜ ๋™์•ˆ ๋ฐ˜๋ณตํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ ์‚ฌ์šฉ
  • ๋ฒ”์œ„ ์—ฐ์‚ฐ์ž๋Š” a...b ๋˜๋Š” a..<b๋กœ ํ‘œํ˜„ 
for ์ž„์‹œ์ƒ์ˆ˜ in ๋ฒ”์œ„ { 
    /* ์‹คํ–‰ ๊ตฌ๋ฌธ */
}

[์˜ˆ๋ฌธ - for๋ฌธ์œผ๋กœ 1๋ถ€ํ„ฐ 10๊นŒ์ง€์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๊ธฐ]

for x in 1...10{
    print(x)
}

[์˜ˆ๋ฌธ - 1๋ถ€ํ„ฐ 100๊นŒ์ง€์˜ ํ•ฉ ๊ตฌํ•˜๊ธฐ]

 

//1~100๊นŒ์ง€์˜ ํ•ฉ ๊ตฌํ•˜๊ธฐ
var total:Int = 0
for x in 1...100{
    print(x) 
    total = total + x
}
print("total = \(total)")	// total = 5050

๐Ÿ–ค for๋ฌธ์€ ์ปฌ๋ ‰์…˜ ํƒ€์ž…์—์„œ ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉ

// ๋ฐฐ์—ด์—์„œ
let integers = [1, 2, 3]
for i in integers {
    print(i)
}

// Dictionary์—์„œ
let people = ["yeon": 10, "eric": 15, "mike": 12]
for (name, age) in people {		//name: key, age:value
    print("\(name): \(age)")
}

// Set์—์„œ
let localNumber: Set<Int> = [1,2,3]
for i in localNumber{
    print(i)
}

๐Ÿ–ค for + where

  • For๋ฌธ ๋ฐ˜๋ณต ์‹œ, ์กฐ๊ฑด์— ๋งž๋Š” ๋ถ€๋ถ„๋งŒ ๋ฐ˜๋ณตํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ
var even: [Int] = []
for i in 1...10 where i%2==0 {
    even.append(i)
}
print("10 ์ดํ•˜ ์ง์ˆ˜๋“ค : \(even)") //10 ์ดํ•˜ ์ง์ˆ˜๋“ค : [2, 4, 6, 8, 10]

๐ŸŽ while ๋ฌธ

  • while๋ฌธ์€ ์กฐ๊ฑด์‹์„ ๊ฒ€์‚ฌํ•˜์—ฌ ์กฐ๊ฑด์‹์ด ์ฐธ์ด๋ฉด ๊ณ„์† ๊ฒ€์‚ฌ๋ฅผ ์ง„ํ–‰ํ•˜๊ณ  ๊ฑฐ์ง“์ผ ๊ฒฝ์šฐ while๋ฌธ์„ ์ข…๋ฃŒ.
  • break์ด๋‚˜ continue๊ฐ™์€ ๋ช…๋ น์–ด๋ฅผ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
  • (break - ๋ฐ˜๋ณต๋ฌธ ํƒˆ์ถœ, continue - continue ์•„๋ž˜ ์ฝ”๋“œ๋Š” ์‹คํ–‰๋˜์ง€ ์•Š๊ณ  ๊ฑด๋„ˆ๋›ด ๋’ค ๋ฐ˜๋ณต์„ ๊ณ„์†ํ•จ)
while ์กฐ๊ฑด {
    /* ์‹คํ–‰ ๊ตฌ๋ฌธ */
}
var integers = [1, 2, 3]

while integers.count > 1 {
    integers.removeLast()
    print(integers)
}

[์˜ˆ๋ฌธ- while๋ฌธ์œผ๋กœ 1๋ถ€ํ„ฐ 10๊นŒ์ง€์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๊ธฐ]

var x = 1
while x <= 10 {
    print(x)
    x += 1
}

๐Ÿ–ค repeat-while ๊ตฌ๋ฌธ

  • ๊ธฐ์กด ์–ธ์–ด์˜ do-while ๊ตฌ๋ฌธ๊ณผ ํ˜•ํƒœ ๋ฐ ๋™์ž‘์ด ์œ ์‚ฌ
  • Repeat ๋ถ€๋ถ„์˜ ์ฝ”๋“œ๋ฅผ ์ˆ˜ํ–‰ํ•œ ํ›„, While ๋ฌธ ์˜†์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ฉด ๋ฐ˜๋ณต, ์•„๋‹ˆ๋ฉด ํƒˆ์ถœํ•˜๋Š” ๋ฐฉ์‹
repeat {
    /* ์‹คํ–‰ ๊ตฌ๋ฌธ */
} while ์กฐ๊ฑด
var integers = [1, 2, 3]

repeat {
    integers.removeLast()
    print(integers)
} while integers.count > 0
728x90
๋ฐ˜์‘ํ˜•