HR's Blog

Swimming 🏊 in the sea🌊of code!

0%

Defer

.

A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.

1
2
3
defer {
statuments
}
1
2
3
4
5
6
7
8
9
10
11
func f() {
defer { print("First") }
defer { print("Second") }
defer { print("Third") }
print("Four")
}
f()
// Prints "Four"
// Prints "Third"
// Prints "Second"
// Prints "First”

Alamofire中用defer来确保get和set中的操作能线程安全

1
2
3
4
5
6
7
8
9
10
subscript(task: URLSessionTask) -> Request? {
get {
lock.lock(); defer { lock.unlock() }
return requests[task.taskIdentifier]
}
set {
lock.lock(); defer { lock.unlock() }
requests[task.taskIdentifier] = newValue
}
}

defer 的 block 执行顺序和书写的顺序是相反的,这种相反的顺序是必要的,是为了确保每样东西的 defer block 在被创建的时候,该元素依然在当前上下文中存在。