๐Ÿ˜ดlazy ์•Œ์•„๋ณด๊ธฐ

sangheeยท2021๋…„ 8์›” 27์ผ
0

๐ŸšฉiOS

๋ชฉ๋ก ๋ณด๊ธฐ
12/18
post-thumbnail
post-custom-banner

๐Ÿ˜ดlazy

A lazy stored property is a property whose initial value is not calculated until the first time it is used.

lazy ๋ณ€์ˆ˜๋Š” ์ฒ˜์Œ ์‚ฌ์šฉ๋˜๊ธฐ ์ „๊นŒ์ง€ ์—ฐ์‚ฐ๋˜์ง€ ์•Š๋Š”๋‹ค.

lazy ์˜ˆ์‹œ

๊ฐœ๋ฐœ์ž๋Š” ์ฒ˜์Œ๋ถ€ํ„ฐ ๋ฉ”๋ชจ๋ฆฌ ํ• ๋‹น์„ ๊ณ ๋ คํ•œ ์ตœ์ ํ™”๋œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์•ผ ํ•œ๋‹ค. ์ฝ”๋“œ ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด, InterviewCandidate ๊ตฌ์กฐ์ฒด์—์„œ, ์‚ฌ์šฉ์ž๊ฐ€ ios๋ฅผ ์„ ํƒํ•˜๋Š”์ง€, android๋ฅผ ์„ ํƒํ•˜๋Š” ์ง€์— ๋”ฐ๋ผ isiOS ๋ณ€์ˆ˜๊ฐ€ ๊ฒฐ์ •๋œ๋‹ค. person1์˜ isiOS๊ฐ’์ด true์ด๋‹ค. printํ•จ์ˆ˜์—์„œ ํ˜ธ์ถœ๋˜๋ฉด์„œ iOSResumeDescription์ด ์ดˆ๊ธฐํ™”๋˜์—ˆ๋‹ค. ๋ฐ˜๋ฉด์— androidResumeDescription๋Š” nil์ด ๋œ๋‹ค.

import UIKit

struct InterviewCandidate {
    var isiOS:Bool?
    
    lazy var iOSResumeDescription: String = {
        return "I am an iOS developer"
    }()
    lazy var androidResumeDescription: String = {
        return "I am an android developer"
    }()
}

var person1 = InterviewCandidate()
person1.isiOS = true

if person1.isiOS! {
    print(person1.iOSResumeDescription)
} else {
    print(person1.androidResumeDescription)

}

ํŠน์„ฑ

  1. ํ•ด๋‹น ์†์„ฑ์„ ์ฝ์„ ๋•Œ๋งŒ ์‹คํ–‰๋œ๋‹ค. ๋”ฐ๋ผ์„œ ํ•ด๋‹น ์†์„ฑ์ด ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ๋ถˆํ•„์š”ํ•œ ํ• ๋‹น ๋ฐ ๊ณ„์‚ฐ์„ ํ”ผํ•  ์ˆ˜ ์žˆ๋‹ค.
  2. lazy๋ฅผ let๊ณผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค. ์ฒ˜์Œ ์‚ฌ์šฉ๋  ๋•Œ ๊ฐ’์ด ์ƒ๊ธฐ๊ธฐ์— var๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉ๋˜์–ด์•ผ ํ•œ๋‹ค.
  3. computed property๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค. ์ฒ˜์Œ ์‚ฌ์šฉํ•  ๋•Œ ๋ฉ”๋ชจ๋ฆฌ์— ๊ฐ’์„ ์˜ฌ๋ฆฌ๊ณ  ๊ทธ ์ดํ›„์—๋Š” ๊ทธ ๊ฐ’์„ ์‚ฌ์šฉํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ๊ฐ’์„ ์—ฐ์‚ฐํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋Š” computed property์™€๋Š” ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.
  4. struct๋‚˜ class์™€ ํ•จ๊ป˜ ์“ธ ์ˆ˜ ์žˆ๋‹ค.

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

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

profile
๐Ÿ‘ฉโ€๐Ÿ’ป
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€