Open chaneeii opened 2 years ago
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()
}
์,, 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/
defer ๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ์ฝ๋๊ฐ ๋ธ๋ก์ ๋น ์ ธ๋๊ฐ๊ธฐ ์ ์ ๋ฌด์กฐ๊ฑด ์คํ๋์ด์ผํฉ๋๋ค!
๊ทธ๋์ ์๋ฌ์ฒ๋ฆฌํ ๋ ์ข์ต๋๋ค