Pljeskavica
Pljeskavica

Reputation: 114

Access a parent class from an enum

So I created a class and typecasted one of the variables to be from an enum i created. The enum has a variable named description that I call and put on the page so that as the variable changes status its description on the page will update.

That part is fine and dandy. But I would like to put a variable in the description, but have it reference the variable from its object from that class.

Here is an example:

class room: NSObject{
    var roomNumber :Int
    var status: requestStatus = .none
    var assignedAssociate: String?

    init(roomNumber:Int){
        self.roomNumber = roomNumber
    }
}

enum requestStatus {
    case waitingForHelp = "Waiting For Help"
    case beingHelped = "Being helped"
    case requestClosed
    case none

    var description: String {
        switch self {
        case .waitingForHelp: return "Needs Help\n "
        case .beingHelped: if return "Being Helped\n by \(super.assignedAssociate)"
        case .requestClosed: return "Completed"
        case .none: return ""
        }
    }
}

So as you can see, I would like to reference assignedAssociate from the object that was instantiated from the room class inside the description for the enum beingHelped.

I just wrote in super.assignedAssociate so that you could see kinda what I wanted to do.

Oh and before everyone jumps on me, I have spend a while trying to find the information on this but swift is still so new its hard to find good sources for this stuff.

Thanks!

Upvotes: 2

Views: 1736

Answers (1)

Rob Napier
Rob Napier

Reputation: 299643

Things do not automatically know what contains them (this is true in every language I know). You will need to store the information in the enum using associated data. For example, I would probably implement it this way:

struct Room {
    let roomNumber: Int
    var status: RequestStatus?

    init(roomNumber: Int) {
        self.roomNumber = roomNumber
    }
}

enum RequestStatus {
    case WaitingForHelp
    case BeingHelped(associate: String)
    case Closed

    var description: String {
        switch self {
        case .WaitingForHelp: return "Needs Help"
        case .BeingHelped(let associate): return "Being Helped by \(associate)"
        case .Closed: return "Completed"
        }
    }
}

Note how I removed assignedAssociate. This was intentional. Instead, that information is attached to the status when the status is BeingHelped.

Also note that I removed the .none case. If the status may be "nothing" that is generally better indicated with an Optional. If you really do want an "unassigned status", then you should call it Unassigned or something similar. None looks too much like Optional.None and this can lead to surprising compiler behavior. (Also note that all types and enum values should have a leading cap.) Personally, I'd probably just get rid of the Optional, too. Can there really be "no status?"

Upvotes: 3

Related Questions