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 :)
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.
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.
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.
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).
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With