Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save zaimramlan/729da076abff5dd7bdeeb95ab05e9f4e to your computer and use it in GitHub Desktop.

Select an option

Save zaimramlan/729da076abff5dd7bdeeb95ab05e9f4e to your computer and use it in GitHub Desktop.

Revisions

  1. zaimramlan revised this gist Aug 20, 2018. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions breaking_strong_reference_cycle_in_closures.swift
    Original file line number Diff line number Diff line change
    @@ -29,6 +29,7 @@ class User {

    let fullName: () -> String

    // do closure to simulate codes going into and out of scope
    do {
    let u = User(firstName: "Johnny", lastName: "English")
    fullName = u.fullName
  2. zaimramlan created this gist Aug 20, 2018.
    39 changes: 39 additions & 0 deletions breaking_strong_reference_cycle_in_closures.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    import Foundation

    class User {
    var firstName: String
    var lastName: String

    // Comment this to see strong reference cycle
    lazy var fullName: () -> String = {
    [weak self] in
    guard let strongSelf = self else { return "No name specified." }
    return "\(strongSelf.firstName) \(strongSelf.lastName)"
    }

    // Uncomment this to see strong reference cycle
    // lazy var fullName: () -> String = {
    // return "\(self.firstName) \(self.lastName)"
    // }

    init(firstName: String, lastName: String) {
    self.firstName = firstName
    self.lastName = lastName
    print("\(User.self) \(firstName) \(lastName) initialised.")
    }

    deinit {
    print("Deallocating \(User.self) object.")
    }
    }

    let fullName: () -> String

    do {
    let u = User(firstName: "Johnny", lastName: "English")
    fullName = u.fullName

    print(fullName())
    }

    print(fullName())