ForEach

  • array, ranges์™€ ํ•จ๊ป˜ ๋ฐ˜๋ณต ์ž‘์—…์„ ํ†ตํ•ด ์—ฌ๋Ÿฌ ๋ทฐ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ์Œ
  • ํด๋กœ์ ธ๋ฅผ ํ†ตํ•ด ์‹คํ–‰๋˜๋ฉฐ loop์˜ ๋ชจ๋“  ์•„์ดํ…œ์„ ํ•œ๋ฒˆ์”ฉ ์ˆœํ™˜ํ•˜๊ฒŒ ๋จ

 

class test {
    init() {
        let titles = ["a", "b", "c", "d", "e"]
        self.loopAllItems(items: titles)
    }
    
    func loopAllItems(items: [String]) {
        items.forEach { print($0) }
    }
}
  • ForEach๋Š” ๊ธฐ์กด์— Swift์—์„œ ์‚ฌ์šฉํ•œ ๊ณ ์ฐจ ํ•จ์ˆ˜ forEach์™€ ๋™์ž‘๊ณผ ์‚ฌ์šฉ๋ฒ•์ด ๊ฐ™์Œ
        ScrollView {
            ForEach(0 ..< 100) {
                Text("\($0)")
            }
        }
  • ForEach๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ฐ˜๋ณต๋˜๋Š” ๋ทฐ๋ฅผ ๊ฐ„๋‹จํ•œ ์ฝ”๋“œ๋กœ ํ™”๋ฉด์— ๊ทธ๋ ค ์ค„ ์ˆ˜ ์žˆ์Œ

์˜ˆ์‹œ ์ฝ”๋“œ

enum StudentType: String {
    case elementary = "์ดˆ๋“ฑํ•™๊ต"
    case middle = "์ค‘ํ•™๊ต"
    case high = "๊ณ ๋“ฑํ•™๊ต"
}
  • ํ•™์ƒ ํƒ€์ž…์„ enum์œผ๋กœ ๊ด€๋ฆฌ
    let types: [StudentType] = [.elementary, .middle, .high]
    @State private var selectedType: StudentType = .elementary
  • ๋‘ ํ”„๋กœํผํ‹ฐ๋ฅผ ์ƒ์„ฑํ•ด ์คŒ. typs๋Š” ํ”ผ์ปค์—์„œ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋Š” ํƒ€์ž…. selectedType์€ ํ”ผ์ปค์—์„œ ์„ ํƒํ•œ ํ•™์ƒ์˜ ํƒ€์ž…์„ ์ €์žฅํ•˜๋Š” ํ”„๋กœํผํ‹ฐ๋กœ @Sate property wrapper์„ ์‚ฌ์šฉํ•˜์—ฌ ์„ ์–ธํ•ด์„œ ํ˜„์žฌ ์‚ฌ์šฉ์ž๊ฐ€ ์„ ํƒํ•œ ์„ ํƒ๊ฐ’์„ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์คŒ
    var body: some View {
        NavigationView {
            Form {
                Picker("ํ•™์ƒ์˜ ์†Œ์†์„ ์„ ํƒํ•˜์„ธ์š”.", selection: $selectedType) {
                    ForEach(types, id: \.self) {
                        Text($0.rawValue)
                    }
                }
            }
        }
    }
  • selectedType์ด two binding์œผ๋กœ ์—ฐ๊ฒฐ๋จ
  • ForEach๋ฅผ ์‚ฌ์šฉํ•ด์„œ types์˜ ๋ชจ๋“  ๊ฐ’์„ Text View๋กœ ๋ฐ˜ํ™˜ํ•ด ์คŒ
  • ForEach์˜ ์ฒซ๋ฒˆ์งธ ์ธ์ž๋Š” ๋ฃจํ”„๋ฅผ ๋Œ๋ฆด ์–ด๋ ˆ์ด๋‚˜ ranges๋ฅผ ์ „๋‹ฌ
  • ๋‘ ๋ฒˆ์งธ ์ธ์ž์ธ id๋Š” SwiftUI์˜ ํŠน์„ฑ ๋•Œ๋ฌธ์— ์กด์žฌํ•˜๋Š” ๊ฐ’. ์Šคํฌ๋ฆฐ์—์„œ ๊ฐ ๋ทฐ๋Š” ๊ณ ์œ  ์‹๋ณ„ ๊ฐ€๋Šฅํ•œ id ๊ฐ’์„ ๊ฐ€์ ธ์•ผ ํ•˜๊ณ  ๋ณ€ํ™”๊ฐ€ ์ผ์–ด๋‚  ๋•Œ ์‹๋ณ„์ด ๊ฐ€๋Šฅํ•จ

 

 

 

์ฐธ๊ณ  ์‚ฌ์ดํŠธ

https://www.hackingwithswift.com/books/ios-swiftui/creating-views-in-a-loop