Friday, November 2, 2018

The Power of Key Paths in Swift

John Sundell:

Let’s see if key paths again can help us make the above syntax a bit simpler, and if we also can get rid of that weak self dance we so often have to do (and with it - the risk of accidentally introducing retain cycles if we forget to capture a weak reference to self).

Since all we’re really doing above is to take the value that was passed to our closure and assign it to a property on our view controller - wouldn’t it be cool if we were actually able to pass the setter for that property as a function? That way we could pass that function directly as the completion handler to our load method and everything would just work.

To make that happen, first let’s define a function that lets us convert any writable key path into a closure that sets the property for that key path. For this, we’ll use the ReferenceWritableKeyPath type, since we want to restrict this to reference types only (otherwise we’d only make changes to a local copy of a value). Given an object and a key path for that object, we’ll automatically capture the object as a weak reference and assign the property matching the key path once our function gets called - like this[…]

Comments RSS · Twitter

Leave a Comment