chaneeii / iOS-Study-Log

โœจ iOS์— ๋Œ€ํ•ด ๊ณต๋ถ€ํ•œ ๊ฒƒ๋“ค์„ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค โœจ
18 stars 0 forks source link

๐Ÿค› defer, ๋’ท์ˆ˜์Šต์„ ๋ถ€ํƒํ•ด #57

Open chaneeii opened 2 years ago

chaneeii commented 2 years ago

๊ณต์‹๋ฌธ์„œ : https://docs.swift.org/swift-book/ReferenceManual/Statements.html#grammar_defer-statement

defer ๊ตฌ๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๋ธ”๋ก์„ ๋น ์ ธ๋‚˜๊ฐ€๊ธฐ ์ „์— ๋ฌด์กฐ๊ฑด ์‹คํ–‰๋˜์–ด์•ผํ•ฉ๋‹ˆ๋‹ค!

defer {
    //  ๋น ์ ธ๋‚˜๊ฐ€๊ธฐ ์ „์— ์‹คํ–‰ํ•  ๋‚ด์šฉ
}

๊ทธ๋ž˜์„œ ์—๋Ÿฌ์ฒ˜๋ฆฌํ• ๋•Œ ์ข‹์Šต๋‹ˆ๋‹ค

chaneeii commented 2 years ago

defer ํ™œ์šฉํ•ด๋ณด์ž

defer ์ œ์ผ ๊ถ๊ธˆํ–ˆ๋˜๊ฒŒ, ์Œ,, ๊ทธ๋ž˜์„œ ์–ธ์ œ์“ฐ์ง€..? lock ํ•œ๋‹ค๋Š”๊ฑฐ ๊ทธ๋Ÿฐ๊ฑฐ ๋ง๊ณ  ์‹ค์ œ๋กœ! ์š”๊ฒŒ ๊ถ๊ธˆํ–ˆ์Šต๋‹ˆ๋‹ค

์•„๋ž˜ ๋‚ด์šฉ๋“ค ๋ณด๊ณ  ๊ฐํƒ„ํ•˜๋ฉด์„œ ์ •๋ฆฌํ•ด๋ด…๋‹ˆ๋‹ค

๋ ˆ์ด์•„์›ƒ ์—…๋ฐ์ดํŠธ ํ• ๋•Œ!

์™€,, ์ด๊ฑฐ ํ˜๋ช…์ ์ธ๋ฐ,,, ๋ฐ”๋กœ ์ ์šฉํ•˜๋ ค๊ตฌ์š” setNeedsLayout ์™€ layoutIfNeeded ์„ ์‚ฌ์šฉํ• ๋•Œ ํ™œ์šฉํ•˜๋ฉด ๋„ˆ๋ฌด ์ข‹์Œ!

func reloadAuthorsData() {
    defer {
        self.setNeedsLayout() 
    }

    removeAllViews()

    guard let dataSource = quotingDataSource else { return }

    let itemsCount = dataSource.numberOfItems(in: self)

    for index in itemsCount.indices {
        let view: AuthorView = getViewForIndex(index)

        addSubview(view)

        authorViews.append(view)
    }
}
func updateViewContstraints() {
    defer {
        self.layoutIfNeeded()
    }

    // One conditional statement to check for constraint and can return early

    // Another statement to update another constraint
}

๋„คํŠธ์›Œํ‚น ์ฒ˜๋ฆฌํ• ๋–„!

์š”๊ฑด ๋ช‡๋ฒˆ๋ณธ,, ์š”๋Ÿฌ๋ฉด ์—๋Ÿฌ๋ฅผ ํ™•์‹คํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ• ์ˆ˜์žˆ๊ฒŸ์ฃ ?

func fetchQuotes(from url: URL, completion: @escaping (Result<[Quote], Error>) -> ()) {
    var result: Result<[Quote], Error>

    defer {
        completion(result)
    }

    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        if let error = error {
            result = .failure(error)
        }

        guard let response = response else {
            result = .failure(URLError(.badServerResponse))
        }

        guard let data = data else {
            result = .failure(QuoteFetchError.missingData)
        }

        result = .success(quoteResponse(for: data))
    }
    task.resume()
}

LoadingIndicator ์ฒ˜๋ฆฌํ• ๋•Œ

์™€,, fancy ํ•˜๋‹ค..! ํ• ์ •๋„๋กœ ๊น”๋”ํ•ด์ง€๋„ค์š”!

func performLogin() {
    shouldShowProgressView = true

    defer {
        shouldShowProgressView = false
    }

    do {
        let _ = try await LoginManager.performLogin()

        DispatchQueue.main.async {
            self.coordinator?.successfulLogin()
        }

    } catch {
        let error = error
        showErrorMessage = true
    }
}

ref: https://blog.logrocket.com/complete-guide-swift-defer-statement/