Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access passed Enum argument in Swift 3

Tags:

swift

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 :)

like image 447
DookieMan Avatar asked Mar 22 '17 17:03

DookieMan


People also ask

Can enum inherit Swift?

In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.

Can enum conform to Swift protocol?

Yes, enums can conform protocols. You can use Swift's own protocols or custom protocols. By using protocols with Enums you can add more capabilities.

How does enum work in Swift?

Enumerations (or enums for short) in Swift define a common type for a group of related values. According to the Swift documentation, enums enable you to work with those values in a type-safe way within your code. Enums come in particularly handy when you have a lot of different options you want to encode.

What is raw value in enum Swift?

Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e. So, A has a fixed raw value of 0 , B of 1 etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case).


1 Answers

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)
    }
}
like image 195
dmorrow Avatar answered Sep 22 '22 08:09

dmorrow