Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - return itself property on getter and set itself on setter

Is anyway to return itself property in the getter and set itself on the setter? Because I just want to print a log inside the getter and the setter and thats it.

For example I trying to do something like this:

private(set) var internetConnectionAvailable: Bool {
    get {
        logger.debug("verifying internet connection")
        // here return itself property
    }
    set {
        logger.debug("changing internet connection")
        // here set itself
    }
}

If I return self.internetConnectionAvailable on the getter I get:

Linker command failed with exit code 1

when I try to compile the project.

I'm trying to do that because I don't want to create an extra private property to store the get and the set. I'm looking if there are something different to achieve that.

like image 992
pableiros Avatar asked Jul 18 '16 16:07

pableiros


1 Answers

EDIT: I note that you said you don't want to create an extra private property. Then sorry. No. Not unless you make this an NSManagedObject subclass (and hook into the willAccessValueForKey system), or otherwise hook into the ObjC runtime on an NSObject (you could swizzle your own getter for instance to add logging; don't laugh, I've done that before). But all of these approaches are insane in Swift (and insane in ObjC; I only used them for debugging). Just make the backing variable.

If you only wanted to log the setter, then this would be straightforward: use willSet rather than set. But logging the getter requires implementing it all by hand. You do that with a private backing variable.

private var _internetConnectionAvailable: Bool
private(set) var internetConnectionAvailable: {
    get {
        logger.debug("verifying internet connection")
        return _internetConnectionAvailable
    }
    set {
        logger.debug("changing internet connection")
        _internetConnectionAvailable = newValue
    }
}

Once you define get yourself, you've said you don't want the default handling, which means you get no automatic backing variable.

like image 82
Rob Napier Avatar answered Sep 22 '22 01:09

Rob Napier