A Swift micro-framework to easily deal with weak references to self inside closures

Overview

WeakableSelf

platforms pod Carthage compatible

Context

Closures are one of Swift must-have features, and Swift developers are aware of how tricky they can be when they capture the reference of an external object, especially when this object is self.

To deal with this issue, developers are required to write additional code, using constructs such as [weak self] and guard, and the result looks like the following:

service.call(completion: { [weak self] result in
    guard let self = self else { return }
    
    // use weak non-optional `self` to handle `result`
})

Purpose of WeakableSelf

The purpose of this micro-framework is to provide the developer with a helper function weakify that will allow him to declaratively indicate that he wishes to use a weak non-optional reference to self in closure, and not worry about how this reference is provided.

Usage

Using this weakify function, the code above will be transformed into the much more concise:

import WeakableSelf

service.call(completion: weakify { strongSelf, result in    
    // use weak non-optional `strongSelf` to handle `result`
})

weakify works with closures that take up to 7 arguments.

Installation

Requirements

  • Swift 4.2+
  • Xcode 10+

CocoaPods

Add the following to your Podfile:

pod "WeakableSelf"

Carthage

Add the following to your Cartfile:

github "vincent-pradeilles/weakable-self"

You might also like...
Measure Swift code metrics and get reports in Xcode, Jenkins and other CI platforms.
Measure Swift code metrics and get reports in Xcode, Jenkins and other CI platforms.

Taylor ⚠️ Taylor is DEPRECATED. Use SwiftLint instead. A tool aimed to increase Swift code quality, by checking for conformance to code metrics. Taylo

Swift-lint-plugin - A SwiftPM plugin that adds a linting command

SwiftLintPlugin This is a SwiftPM plugin that adds a lint command. SwiftPM plugi

Aplicação Basica em Swift desenvolvida com o intuito de aplicar os conceitos estudados
Aplicação Basica em Swift desenvolvida com o intuito de aplicar os conceitos estudados

Via Cep iOS Sobre - Interface do Usuario - Tecnologias - Requisitos - Autor Projeto 🛑 FINALIZADO 🛑 Sobre A Aplicação consiste em fazer buscas usando

A Swift micro-framework to easily deal with weak references to self inside closures

WeakableSelf Context Closures are one of Swift must-have features, and Swift developers are aware of how tricky they can be when they capture the refe

A simple solution for tiring [weak self] in swift

Weakifiable A simple solution for tiring [weak self] in swift Usage give this repo a Star ⭐️ Add EBWeakifiable to your Project. simply after each clos

SwiftUI project demonstrating how weak self works

SwiftUI-weak-self SwiftUI project demonstrating how weak self works Inspired by Swiftful

📱💬🚦 TinyConsole is a micro-console that can help you log and display information inside an iOS application, where having a connection to a development computer is not possible.
📱💬🚦 TinyConsole is a micro-console that can help you log and display information inside an iOS application, where having a connection to a development computer is not possible.

TinyConsole TinyConsole is a tiny log console to display information while using your iOS app and written in Swift. Usage Wrap your Main ViewControlle

A Swift sample code to reads ISO 10303-21 exchange structures (STEP P21 files for AP242) split into multiple files using external references approach.

multipleP21ReadsSample A Swift sample code to reads ISO 10303-21 exchange structures (STEP P21 files for AP242) split into multiple files using extern

SwiftySound is a simple library that lets you deal with Swift sounds easily

SwiftySound Overview SwiftySound is a simple library that lets you deal with Swift sounds easily. Static methods Sound.play(file: "dog.wav") Sound.pla

PySwiftyRegex - Easily deal with Regex in Swift in a Pythonic way

PySwiftyRegex Easily deal with Regex in Swift in a Pythonic way.

Easily deal with Regex in Swift in a Pythonic way

PySwiftyRegex Easily deal with Regex in Swift in a Pythonic way. 简体中文 日本語 한국어 This is Easy import PySwiftyRegex if let m = re.search("[Tt]his is (.*?

LaiFeng IOS Live Kit,H264 and AAC Hard coding,support GPUImage Beauty, rtmp transmission,weak network lost frame,Dynamic switching rate
LaiFeng IOS Live Kit,H264 and AAC Hard coding,support GPUImage Beauty, rtmp transmission,weak network lost frame,Dynamic switching rate

LFLiveKit LFLiveKit is a opensource RTMP streaming SDK for iOS. Features Background recording Support horizontal vertical recording Support Beauty Fac

Short examples and references to work with property wrappers in SwiftUI.

A Colection of useful playgrounds This repo contains a collection of useful swift playgrounds. PropertyWrappers Playground Contains small example of u

Folder References With Xcode Gen

FolderReferencesWithXcodeGen How to Build and Run Install dependencies # Install

Elegant manager to easily deal with UIPickerView
Elegant manager to easily deal with UIPickerView

PickL PickL is an elegant manager to easily deal with UIPickerView. You don't have to implement a logic for UIPickerViewDataSource and UIPickerViewDel

TupleResult - A micro library that easily converts tuple result into Swift.Result

TupleResult A micro library that easily converts c-style tuple result into Swift

T - A simple testing framework using closures and errors

t Quickly test expectations What is t? t is a simple testing framework using clo

A micro-framework that leverages Swift Property Wrappers to implement the Service Locator pattern

Locatable Context Locatable is a Swift micro framework that leverages Property Wrappers to implement the Service Locator pattern, through a custom att

Aftermath is a stateless message-driven micro-framework in Swift
Aftermath is a stateless message-driven micro-framework in Swift

Aftermath is a stateless message-driven micro-framework in Swift, which is based on the concept of the unidirectional data flow architecture.

Comments
  • Order issue

    Order issue

    Hi! Thanks for this great implementation!

    Although, its usage really looks like another operator that can be found in RxSwiftExt (I don't know if you ever heard of if :trollface: ) and the order in the arguments isn't consistent between the two methods

    for now it takes two parametters, first the passed parameter and then the self which results in a call like this :

       .subscribe(onNext: weakify { data, strongSelf in
                 strongSelf.doSomething(with: data)
                })
    

    I find it kind of awkward considering that when we use .withUnretained(self) the order is reversed.

    .withUnretained(self)
    .subscribe(onNext: { strongSelf, data in
                 strongSelf.doSomething(with: data)
                })
    

    Also in the general case in closures the compiler enforces the [weak/unretained self] to be before the arguments of the closure

    .subscribe(onNext: { [unretained self] data in
                 self.doSomething(with: data)
                })
    

    what do you think about changing the order in the new method ? If you agree I can obviously make a pull request with the changes :)

    Cheers!

    opened by HugoSay 0
Owner
Vincent Pradeilles
French iOS software engineer, working in Lyon, France 🇫🇷
Vincent Pradeilles
Flexible bug report framework for iOS

Clue is a simple smart-bug report framework for iOS, which allows your users to record full bug/crash report and send it to you as a single .clue file

Ahmed Sulaiman 279 Nov 3, 2022
Lint anything by combining the power of Swift & regular expressions.

Installation • Getting Started • Configuration • Xcode Build Script • Donation • Issues • Regex Cheat Sheet • License AnyLint Lint any project in any

Flinesoft 116 Sep 24, 2022
A tool for Swift code modification intermediating between code generation and formatting.

swift-mod A tool for Swift code modification intermediating between code generation and formatting. Overview swift-mod is a tool for Swift code modifi

Ryo Aoyama 95 Nov 3, 2022
SwiftCop is a validation library fully written in Swift and inspired by the clarity of Ruby On Rails Active Record validations.

SwiftCop is a validation library fully written in Swift and inspired by the clarity of Ruby On Rails Active Record validations. Objective Build a stan

Andres Canal 542 Sep 17, 2022
A command-line tool and Xcode Extension for formatting Swift code

Table of Contents What? Why? How? Command-line tool Xcode source editor extension Xcode build phase Via Applescript VSCode plugin Sublime Text plugin

Nick Lockwood 6.3k Jan 8, 2023
A tool to enforce Swift style and conventions.

SwiftLint A tool to enforce Swift style and conventions, loosely based on the now archived GitHub Swift Style Guide. SwiftLint enforces the style guid

Realm 16.9k Jan 9, 2023
An Xcode formatter plug-in to format your swift code.

Swimat Swimat is an Xcode plug-in to format your Swift code. Preview Installation There are three way to install. Install via homebrew-cask # Homebrew

Jintin 1.6k Jan 7, 2023
Cross-platform static analyzer and linter for Swift.

Wiki • Installation • Usage • Features • Developers • License Tailor is a cross-platform static analysis and lint tool for source code written in Appl

Sleekbyte 1.4k Dec 19, 2022
Type-safe observable values and collections in Swift

GlueKit ⚠️ WARNING ⚠️ This project is in a prerelease state. There is active work going on that will result in API changes that can/will break code wh

null 361 Oct 12, 2022
💊 Syntactic sugar for Swift do-try-catch

Fallback Syntactic sugar for Swift do-try-catch. At a Glance value = try fallback( try get("A"), try get("B"), try get("C"), try get("D") ) is

Suyeol Jeon 43 May 25, 2020