DookieMan DookieMan -4 years ago 173
Swift Question

How to access passed Enum argument in Swift 3

I'm having some trouble accessing a parameter that is passed with an enum.

Generic RequestType, more will be included.

enum RequestType {
case flagging(api : FlaggingRequestType)
}


Here is my enum that accepts another FlaggingRequestType (another enum that accepts a string parameter)

enum FlaggingRequestType {
case getFlag(api : String)
}

protocol Requestable {
var requestType : RequestType { get set }
}


Here I build my flagging request

let flaggingRequest = RequestBuilder.buildFlaggingRequest(flagRequest: .getFlag(api: "http://www.apiworld.com"))


Here is my method to actually sends the request from another method.

func sendRequest(for apiRequest : Requestable) {
switch apiRequest.requestType {
case .flagging:
self.flaggingAPI(for: apiRequest)
}
}


The problem is I can't figure out how to access the value passed in the
api
parameter found in
apiRequest
/
flaggingRequest
. Is this possible? I hope this is clear :)

Answer Source

Here's a great link for enums with associated values https://appventure.me/2015/10/17/advanced-practical-enum-examples/#sec-1-5

func sendRequest(for apiRequest : Requestable) {
    switch apiRequest.requestType {
    case .flagging(let api):
        // access api value here
        self.flaggingAPI(for: apiRequest)
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download