Search code examples
swiftswift-extensionscomputed-properties

Is it possible use non read-only computed property in extension?


Is it possible for a computed property in extension to have both getter and setter? Apple's guide does not mention it and the only example I have seen only shows read-only computed property in extension.


Solution

  • Is it possible computed property in extension that has getter and setter?

    Yes.

    Probably one of the most common uses of computed properties in extensions in my experience is providing a wrapper to make easier access to particular properties.

    For example, when we want to modify the border layer, border color, or corner radius of anything out of UIKit, we're stuck going through the layer property.

    But we can extend UIView with a property with both a setter & getter to provide a much more convenient means of changing the properties of its layer:

    extension UIView {
        var borderColor: UIColor? {
            get {
                guard let color = self.layer.borderColor else {
                    return nil
                }
                return UIColor(CGColor: color)
            }
            set {
                self.layer.borderColor = newValue?.CGColor
            }
        }
    }
    

    Moreover, if we really want to, we can leverage the Objective-C run time to emulate stored properties in extensions (which of course mean setting & getting). Take part of this Stack Overflow answer for example:

    private var kAssociationKeyNextField: UInt8 = 0
    
    extension UITextField {
        @IBOutlet var nextField: UITextField? {
            get {
                return objc_getAssociatedObject(self, &kAssociationKeyNextField) as? UITextField
            }
            set(newField) {
                objc_setAssociatedObject(self, &kAssociationKeyNextField, newField, .OBJC_ASSOCIATION_RETAIN)
            }
        }
    }
    

    This serves as just one example of a property in an extension with a setter & getter.