Alexander Held
Alexander Held

Reputation: 13

How to access properties outside of an enum

How can I access my class properties from within an enum contained in this class?

But as soon as I instantiate multiple MyClass, the _toggledOn is the same for all instances.

I hope there is some clean and swifty workaround I don't know. Anyways thank you in advance!


@IBDesignable
class MyClass: UIView, SomeProtocols {

    // MARK: - ENUM
    enum ToggleState {
        case on
        case off

        var color: UIColor {
            switch self {
            case .on:
                return _onColor
            default:
                return _offColor
            }
        }
    }

    // MARK: - STATICS
    private static var _onColor: UIColor = #colorliteral
    private static var _offColor: UIColor = #colorliteral

    // MARK: - IBSTUFF
    @IBInspectable var toggledOffColor: UIColor = #colorliteral {
        didSet {
            MyClass._offColor = toggledOffColor
            updateUI()
        }
    }

    @IBInspectable var toggledOnColor: UIColor = #colorliteral {
        didSet {
            MyClass._onColor = toggledOnColor
            updateUI()
        }
    }

    @IBOutlet weak var background: UIView!

    @IBAction func buttonPressed(_ sender: UIButton) {
        toggleState = toggleState == .off ? .on : .off
    }

    // MARK: - PROPERTIES
    var toggleState: ToggleState = .off {
        didSet { toggle() }
    }


    // MARK: - METHODS
    func updateUI() {
        background.backgroundColor = toggleState.color
        background.layer.addShadow()
    }

    func toggle() {
        background.backgroundColor = toggleState.color
    }
}

Upvotes: 1

Views: 70

Answers (1)

Sweeper
Sweeper

Reputation: 273380

Your _onColor and _offColor are static, so there will not be a separate _onColor and _offColor for each instance of your class.\

You should make _onColor and _offColor non-static, and remove the color property of ToggleState, and instead add such a method in your class:

func color(forToggleState state: ToggleState) {
    switch state {
    case .on:
        return _onColor
    case .off:
        return _offColor
    }
}

Instead of toggleState.color, you should write:

color(forToggleState: toggleState)

color shouldn't be a property of ToggleState because to compute it, you need information from another object.

Upvotes: 1

Related Questions