• Stars
    star
    703
  • Rank 64,412 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ‘·β€β™€οΈ Closure-based delegation without memory leaks

Delegated

Delegated is a super small package that helps you avoid retain cycles when using closure-based delegation.

New Medium post here.

Original Medium post (Delegated 0.1.2) here.

🚨 WARNING! Delegated 2.0 is not compatible with Delegated 0.1.2. If you don't want to migrate your current codebase, stay on Delegated 0.1.2. See documentation for Delegated 0.1.2 here. If you need any help migrating from 0.1.x to 2.0.x, please open an issue.

Usage

Before:

final class TextField {
    var didUpdate: (String) -> () = { _ in }
}

// later...

self.textField.didUpdate = { [weak self] text in
    guard let strongSelf = self else {
        return
    }
    strongSelf.label.text = text
}

After:

final class TextField {
    @Delegated var didUpdate: (String) -> ()
}

// later...

textField.$didUpdate.delegate(to: self) { (self, text) in
    // `self` is weak automatically!
    self.label.text = text
}

No retain cycles! No memory leaks! No [weak self]! πŸŽ‰

Guide

Creating a delegated function

final class TextField {
    @Delegated var didUpdate: (String) -> ()
}

This will only compile for closures that have exactly one argument and no return value. To use any other number of arguments, use this:

final class TextField {
    @Delegated0 var didStartEditing: () -> Void
    @Delegated1 var didUpdate: (String) -> Void
    @Delegated2 var didReplace: (String, String) -> Void
}

Delegated0 - Delegated4 are provided out of the box. Delegated is a typealias for Delegated1.

Registering as a delegate

// somewhere inside init() or viewDidLoad() or similar
self.textField = TextField()
textField.$didUpdate.delegate(to: self) { (self, text) in
    self.label.text = text
}

By default, delegate(to:with:) will wrap self in a weak reference so that you don't need to remember to write [weak self] every time. This is the main feature of Delegated, but if this is not the behavior you want, you can use manuallyDelegate(with:):

// somewhere inside init() or viewDidLoad() or similar
self.textField = TextField()
textField.$didUpdate.manuallyDelegate { (text) in
    print(text)
}

Calling a delegate

final class TextField {
    @Delegated var didUpdate: (String) -> Void
    
    /// ...
    
    private func didFinishEditing() {
        self.didUpdate(self.text)
    }
}

Delegating a function with a return value

If your delegated function is designed to have a return value (non-Void), use @ReturningDelegated wrapper.

final class TextField {
    @ReturningDelegated  var shouldReturn: (String) -> Bool?
    
    @ReturningDelegated0 var shouldBeginEditing: () -> Bool?
    @ReturningDelegated2 var shouldReplace: (String, String) -> Bool?
}

// ...

textField.$shouldReturn.delegate(to: self) { (self, string) -> Bool in
    if string.count > 5 {
        return true
    } else {
        return false
    }
}

IMPORTANT: Make sure that your @ReturningDelegated function returns an optional. It will return nil if no delegate is set.

Default @ReturningDelegated supports exactly one input argument. Use @ReturningDelegated0 - @ReturningDelegated4 if you need a different number of arguments (see above).

Removing a delegate

@Delegated var didUpdate: (String) -> ()
// ...
self.$didUpdate.removeDelegate()

Installation

Swift Package Manager

Delegated is officially available only via Swift Package Manager.

In Xcode 11 or greater, in you project, select: File > Swift Packages > Add Pacakage Dependency

In the search bar type

https://github.com/dreymonde/Delegated

and when you find the package, with the next button you can proceed with the installation.

If you can't find anything in the panel of the Swift Packages you probably haven't added yet your github account. You can do that under the Preferences panel of your Xcode, in the Accounts section.

For command-line based apps, you can just add this directly to your Package.swift file:

dependencies: [
    .package(url: "https://github.com/dreymonde/Delegated", from: "2.1.0"),
]

Manual

Of course, you always have an option of just copying-and-pasting the code - Delegated is just one file, so feel free.

More Repositories

1

Time

πŸ•° Type-safe time calculations in Swift
Swift
1,073
star
2

AppFolder

πŸ—‚ Never use NSSearchPathForDirectoriesInDomains again
Swift
938
star
3

Shallows

πŸ›Ά Your lightweight persistence toolbox
Swift
622
star
4

NiceNotifications

πŸ”” Create rich local notifications experiences on iOS with incredible ease
Swift
269
star
5

Placeholders

πŸ…ΏοΈ Define multiple placeholders for UITextField and animate their change
Swift
199
star
6

ScheduledNotificationsViewController

See all your scheduled local notifications in one place
Swift
170
star
7

DateBuilder

πŸ“† Create dates and date components easily (e.g. "first Thursday of the next month")
Swift
136
star
8

TheGreatGame

πŸ† Open-source first-class iOS & watchOS app dedicated to Women’s Euro 2017
Swift
135
star
9

Paperville

πŸ™ Design a city in Swift code (ο£ΏWWDC 2018 submission, ACCEPTED)
Swift
51
star
10

TelegraphKit

πŸ“œ The ultimate solution for showing ad hoc, server-editable web content (FAQs, Tutorials, Privacy Policy, etc.) in your iOS apps
Swift
51
star
11

DonateToUkraine

πŸ‡ΊπŸ‡¦ Implement "donate to Ukraine" inside your app, with Apple Pay
Swift
25
star
12

Alba

πŸŽ™ Stateful event observing engine [DEPRECATED]
Swift
19
star
13

Avenues

πŸŒ… [WIP] Idiomatic image fetching and caching in Swift.
Swift
13
star
14

Subviews

🧩 @​Subview and other ways of making UIKit more fun to use
Swift
9
star
15

Timers

⏲️ Intuitive Swift timers with automatic memory management
Swift
8
star
16

SwiftyNURE

Swift framework for NURE API (CIST)
Swift
3
star
17

Operacjas

πŸ›  [DEPRECATED] Unlocking the full glory of NSOperations
Swift
2
star
18

Swift-hints

1
star
19

DynamicInstance

Swift
1
star
20

Operations

[WIP] NSOperations for 2018
Swift
1
star
21

uahelp-js-scripts

JavaScript
1
star
22

Avenues-Shallows

Making caching even better
Swift
1
star
23

SofarKit

Access Sofar admin data with Swift [WIP]
Swift
1
star
24

Light

πŸ•Š Super thin networking layer built on top of Shallows
Swift
1
star