Member-only story

Swizzling in Swift

Change the Implementation at Runtime

--

Photo by Javier Allegue Barros on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 11.5, and Swift 5.2.4

Terminology:

Runtime: The period of time where a program is running

Swizzling: Method Swizzling is the process of changing the implementation of an existing selector

Swizzling is called Monkey Patching in some languages, and this moves us towards understanding the attitude of the language feature. Furthermore, some people call it a hack or the nonsensical insult of an anti-pattern.

We are going to explore how this can be used in Swift, and a real example of the use in Swift

Swizzling under the hood

Method Swizzling is about changing the implementation of an existing selector at runtime. This is performed through Swift’s Witness table and the mapping of the underlying functions contained within.

The example project

What we are trying to achieve

The idea is that this project swizzles localizedString(forKey:value:table:) and replaces the bundle path with a given alternative path. In effect, NSLocalizedString is pointed to a different set of localized Strings (for example, we could download a Bundle from an endpoint).

The view of the implementation

Let us be honest here. There isn’t too much going on in the project in this repo- the main screen of the ViewController just displays a UILabel and a UIButton (which doesn’t have any functionality).

Where the project is interesting is throught the tests — if you swizzle the bundle the view controller will display one of two separate Strings.

The tests

The tests use a simple helper function to reference a bundle of Strings from the…

--

--

Responses (1)

Write a response