lazy property๋ฅผ ์‚ฌ์šฉํ•ด๋ณธ ๊ฒฝํ—˜์ด ์žˆ๋‹ค. ํ•ด๋‹น ์•„์ด๋””์–ด๋Š” ํ•จ์ˆ˜ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด์—์„œ ์ฃผ๋กœ ์‚ฌ์šฉํ•œ๋‹ค. ์ด๋ฒˆ์—๋Š” ์ง€์—ฐ ๊ณ„์‚ฐ๋ฒ•์ด ๋ฌด์—‡์ธ์ง€, ๊ทธ๋ฆฌ๊ณ  Lazy์™€ unfold sequence์— ๋Œ€ํ•ด ์•Œ์•„๋ณธ๋‹ค.

Lazy Evaluation

  • Lazy Evalutation
  • ํ‘œํ˜„์˜ ํ‰๊ฐ€๋ฅผ ์ตœ๋Œ€ํ•œ ๋Šฆ์ถค
  • Lazy Property
    • ๊ฐ’์„ ์‚ฌ์šฉํ•˜๊ธฐ์ „์—๋Š” ์ƒ์„ฑํ•˜๊ณ  ์žˆ์ง€ ์•Š๋‹ค๊ฐ€ ์ ‘๊ทผํ•˜๋Š” ์ˆœ๊ฐ„ ์ƒ์„ฑ
  • Lazy Collection
    • Element๋“ค์„ ํ•œ๊บผ๋ฒˆ์— ๋ฏธ๋ฆฌ ์—ฐ์‚ฐํ•˜์ง€ ์•Š๊ณ  ํ•„์š”์— ๋”ฐ๋ผ ํ•˜๋‚˜์”ฉ ์ฒ˜๋ฆฌ
    • Collection ๋‚ด๋ถ€ ๊ฐœ์ˆ˜๊ฐ€ 10๋งŒ๊ฐœ
    • map์„ ํ†ตํ•ด transform์„ ํ•˜๋Š” ๊ฒฝ์šฐ
    • ๋งŒ์•ฝ 3๋ฒˆ์ด๋ฉด 30๋งŒ๋ฒˆ์˜ ์—ฐ์‚ฐ
      • ๋งค์šฐ ํฐ ๋น„์šฉ
      • ์ „๋ถ€๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ๋ชฐ๋ผ๋„ ์ผ๋ถ€๋งŒ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ๋น„ํšจ์œจ์ 
  • ์žฅ์ 
    • ์‹œ๊ฐ„์ด ๋งŽ์ด ๊ฑธ๋ฆฌ๋Š” ์—ฐ์‚ฐ์„ ํ•„์š”ํ•  ๋•Œ๊นŒ์ง€ ๋ฏธ๋ฃธ
    • ๋ฌดํ•œ Collection์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Œ
      • 0, 1์ด ๋ฌดํ•œ์ด ๋ฐ˜๋ณต๋˜๋Š” Collection
    • map, flatMap, filter๋“ฑ๋„ lazyํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•ด์„œ ํšจ์œจ ๋†’์€ code๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Œ

Lazy

  • Lazy Property

  • LazySequence

    let array1 = Array(0..<10000)
    let array2 = array1.lazy.map { $0 + 1 }
    print("\(array2[0])", "\(array2[4])")
    • line 2๋ฒˆ์—์„œ ์‹ค์ œ ๊ณ„์‚ฐํ•˜์ง€ ์•Š์Œ
    • 3๋ฒˆ line์—์„œ 0, 4๋งŒ transformํ•˜์—ฌ ์‚ฌ์šฉ๋จ
    • RandomAccessCollection
      • LazyCollectionProtocol
        • LazySequenceProtocol
          • Sequence
          • ์ฆ‰, Sequence์˜ ๋ชจ๋“  ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉ๊ฐ€๋Šฅ
          • ๋™์ž‘๋งŒ lazyํ•˜๊ฒŒ
    • map, flatMap, filter๋Š” ๊ฐ’ ์ ‘๊ทผ ์ „๊นŒ์ง€ ๋™์ž‘ํ•˜์ง€ ์•Š์Œ
    • ์•„์‰ฌ์šด ์ 
      • lazy Property๊ฐ€ RandomAccessCollection์— ์กด์žฌํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ์ ์–ด๋„ ํ•œ๋ฒˆ์€ Collection์„ ๋งŒ๋“ค๊ณ  .lazy๋กœ ์ ‘๊ทผํ•ด์•ผ ํ•จ
      • ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด ๊ฐ™์ด ์ดˆ๊ธฐ๊ฐ’์„ ํ•„์š”๋กœ ํ•˜๋Š” Sequence๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์–ด๋ ค์›€
      • ๋ฌดํ•œ Collection์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์—†์Œ

UnfoldSequence

  • Swift-Evolution 0094
  • ์–ด๋–ค ๊ฐ€๋ณ€ ์ƒํƒœ์— ๋”ฐ๋ผ Closure๋ฅผ ๋ฐ˜๋ณต์ ์œผ๋กœ ์ ์šฉํ•ด์„œ element๋“ค์ด ๋งŒ๋“ค์–ด์ง€๋Š” sequence
  • ๊ฐ element๋Š” lazyํ•˜๊ฒŒ ๊ณ„์‚ฐ๋˜๋ฉฐ ๋ฌดํ•œ์˜ ๊ธธ์ด๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์Œ
  • ์‚ฌ์šฉ๋ฐฉ๋ฒ•
    • ๋ฌดํ•œ Sequence

      let seq = sequence(first: 0.1, next: { $0 * 2 }).dropFirst(5).prefix(10)
      for x in seq {
          NSLog("\(x))
      }
      • ๋งŒ์•ฝ prefix๋กœ ์ œํ•œ์„ ๊ฑธ์ง€ ์•Š์œผ๋ฉด for๋Š” ๋ฌดํ•œ๋ฃจํ”„๊ฐ€ ๋จ
      • dropFirst(n)๋Š” ์•ž์˜ n๊ฐœ๋ฅผ ๋ฒ„๋ฆฌ๋Š” ํ•จ์ˆ˜
    • ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด

      func next(pair: inout (Int, Int)) -> Int {
          pair = (pair.1, pair.0 + pair.1
          return pair.1)
      }
       
      var seq = sequence(state: (0, 1), next: next).prefix(20)
       
      for x in seq {
          print("\(x)")
      }
      • prefix ๊ฑธ์ง€์•Š์œผ๋ฉด overflow
      • inout์„ ์‚ฌ์šฉํ•˜์—ฌ pair์•ˆ์˜ ๊ฐ’์„ ๊ณ„์†ํ•ด์„œ ๋ฐ”๊ฟˆ