Swift: use property observers when defining variables one at a time

The problem with property observers in Swift is that they scatter variables throughout the class, making it difficult to see and understand the properties being used.

Without property observers, you can list all variables and defaults in a single block, one per line, so it's much easier to see the properties of a class.

For example, without property observers:

class User: NSObject, NSCoding {
    // NSCoding Keys
    static let UserKey = "UserKey"
    let Key1 = "Key1"
    let Key2 = "Key2"
    let Key3 = "Key3"

    // Constants
    let Constant1 = "Constant1"
    let Constant2 = "Constant2"
    let Constant3 = "Constant3"

    // Stat Vars
    var var1 = 0
    var var2 = 0
    var var3 = 0

    // Logging Vars
    var lvar1 = 0
    var lvar2 = 0
    var lvar3 = 0

    // Misc Vars
    var mvar1 = 0
    var mvar2 = 0
    var mvar3 = 0
}

      

Is there a way to organize properties like this one per line and also use property observers to work as setters / getters? Basically, the goal is to define properties in one section and where setter / getter functions are needed, define what is elsewhere in the file.

Supposedly not, but hopefully someone has a clever suggestion.

+1


source to share


1 answer


[Note: There is no such thing as a "property observer". Fast variables - not only properties, but also any variable - may be observers setter ( willSet

and didSet

). You cannot watch getting the stored variable. Also, you cannot have a setter observer in a variable let

, because (wait for it) it cannot be set. So my answer is based on mentally modifying your question to fit these facts. However, I really don't understand what the question is, because I don't see in what sense setter observers "scatter variables across the class". However...]

The setter variable observer is part of the variable declaration. It cannot be added later. The closest thing you can do is add a setter observer separately from the variable declaration for the subclass (although this I think would be a very stupid and confusing thing to do gratuitously):



class User {
    var (var1, var2, var3) = (0,0,0) // super neatness
}
class MyUser:User { // add setter observers
    override var var1 : Int {
        didSet {}
        willSet {}
    }
    override var var2 : Int {
        didSet {}
        willSet {}
    }
    override var var3 : Int {
        didSet {}
        willSet {}
    }
}

      

0


source







All Articles