local computed variables
Source: https://www.objc.io/blog/2018/04/10/local-vars/
Sometimes we want to compute the same expression twice in a function. For example, hereโs a simplified version of some XML parsing code we recently wrote:
Note that weโve duplicated thetext.trimmingCharacters(in: .whitespaces)
in two branches. Of course, we can easily pull it out into a variable outside of theif
statement:
This works fine, except that it can really slow down our parsing code: weโre trimming the text for _every _element that we parse, but we only really need it in case oftrk
andele
elements. Iftrimmed
were a struct or class property, we could writelazy
in front of it, but alas, that doesnโt work for a local variable.
Instead, we can maketrimmed
a local computed property, like so:
This will computetrimmed
only when you need it. Of course, this solution has its drawbacks, too: if you access thetrimmed
computed property more than once, it also computes the value more than once. You have to be careful to only use it when you need it, and if you do need it multiple times, cache the value.
The technique above can also work well for complicated loop conditions. For example, hereโs a completely made-up while loop with three conditions:
If we want to group the two queue-related conditions into one, a local computed property can be used:
For more advanced tricks with local properties, watchSwift Talk 61andSwift Talk 63, where we use Swift 4โs KeyPaths to build a new hybrid type, combining useful features of both classes and structs โ a fun way to push the limits of the language!
Last updated