Skip to content

Instantly share code, notes, and snippets.

View almaleh's full-sized avatar
💭
Indexing...

Besher Al Maleh almaleh

💭
Indexing...
View GitHub Profile
// Solution A: Unwind the recursion using DFS
func printXY(_ n: Int) -> [String] {
var explored = Set<Int>()
var stack = [n]
var output = [String]()
while let last = stack.last {
class ViewControllerB: UIViewController {
var workItem: DispatchWorkItem?
override func viewDidLoad() {
let view = self.view
let workItem = DispatchWorkItem {
UIView.animate(withDuration: 1.0) { [weak self] in // this leaks
view?.backgroundColor = .red
}
let view = self.view
let workItem = DispatchWorkItem {
UIView.animate(withDuration: 1.0) { // adding [weak self] here will introduce a cycle
view?.backgroundColor = .red
}
}
self.workItem = workItem
let workItem = DispatchWorkItem { [weak self] in
UIView.animate(withDuration: 1.0) {
self?.view.backgroundColor = .red
}
}
self.workItem = workItem
let workItem = DispatchWorkItem { // <-- first closure
UIView.animate(withDuration: 1.0) { // <-- second closure
self.view.backgroundColor = .red
}
}
self.workItem = workItem
// Can you tell which version has a retain cycle?
// Version A
class ViewControllerA: UIViewController {
var workItem: DispatchWorkItem?
override func viewDidLoad() {
let workItem = DispatchWorkItem {
UIView.animate(withDuration: 1.0) {
let concurrent = DispatchQueue(label: "com.besher.concurrent", attributes: .concurrent)
concurrent.sync {
for _ in 0..<5 { print("🔵") }
}
concurrent.async {
for _ in 0..<5 { print("🔴") }
}
let concurrent = DispatchQueue(label: "com.besher.concurrent", attributes: .concurrent)
concurrent.async {
for _ in 0..<5 { print("🔵") }
}
concurrent.async {
for _ in 0..<5 { print("🔴") }
}
let serial1 = DispatchQueue(label: "com.besher.serial1")
let serial2 = DispatchQueue(label: "com.besher.serial2")
serial1.sync { // <---- we changed this to 'sync'
for _ in 0..<5 { print("🔵") }
}
// we don't get here until first loop terminates
serial2.async {
for _ in 0..<5 { print("🔴") }
}
let serial = DispatchQueue(label: "com.besher.serial")
serial.async {
for _ in 0..<5 { print("🔵") }
}
serial.async {
for _ in 0..<5 { print("🔴") }
}