Sean Sean - 3 years ago 148
Swift Question

How do I verify incoming data for properties?

In my model, I have a singleton class which will contain some global properties and methods. I think I've set up the class correctly but I need a way to verify incoming data for the properties. I'm trying to use

get
and
set
but these seem to need to return void. I can't use init because it's a singleton.

Am I missing something?

final class Globals {

private init(){}

static let sharedInstance = Globals()

//MARK: Properties
private var _peopleCount: Int!

var peopleCount: Int! {
get {
return _peopleCount
}
set(newPeopleCount) {
guard newPeopleCount > 0 else {
return nil // can't return nil here
}
}
}
}

Answer Source

You shouldn't define your variables as implicitly unwrapped optionals unless you have a very good reason to do so.

Your immediate error is that you cannot return a value in a setter, you need to assign the value to the variable there. If you want to mark an invalid value by peopleCount being nil, define peopleCount as Int? and assign to it nil when the check fails.

final class Globals {

    private init(){}

    static let sharedInstance = Globals()

    //MARK: Properties
    private var _peopleCount: Int?

    var peopleCount: Int? {
        get {
            return _peopleCount
        }
        set(newPeopleCount) {
            if let newValue = newPeopleCount, newValue > 0 {
                _peopleCount = newValue
            }
        }
    }
}

For most use cases, there is no need for the private backing variable, you can just use didSet to check the value before assigning it. Thanks for @LeoDabus for the idea in comments.

var peopleCount: Int? {
    didSet {
        if let newValue = peopleCount, newValue > 0 {
            peopleCount = newValue
        } else {
            peopleCount = oldValue
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download