KevinVuD
KevinVuD

Reputation: 611

How to create enum that takes parameter?

This is my enum

enum urlLink: String {
   case linkOne = "http://test.com/linkOne"
}

and it works well in most of my cases. However, I now want to create another link which will takes parameters and it looks like this

"http://test.com/:params/info"

is there a way that I can add string parameter to one of my enum cases so that I can have something like this for linkTwo

enum urlLink: String {
   case linkOne = "http://test.com/linkOne"
   case linkTwo(input: String) = "http://test.com/" + input + "info"
}

Thank you so much!

Upvotes: 1

Views: 73

Answers (1)

Sweeper
Sweeper

Reputation: 274835

You can't add raw values to enums with associated values. You can, however add properties and methods to your enum, so you can do something like this:

enum urlLink: CustomStringConvertible {
    case linkOne
    case linkTwo(input: String)

    var description: String {
        switch self {
        case .linkOne:
            return "http://test.com/linkOne"
        case .linkTwo(let input):
            return "http://test.com/\(input)info"
        }
    }
}

You can also conform to RawRepresentable:

enum urlLink: RawRepresentable {
    case linkOne
    case linkTwo(input: String)

    var rawValue: String {
        switch self {
        case .linkOne:
            return "http://test.com/linkOne"
        case .linkTwo(let input):
            return "http://test.com/\(input)info"
        }
    }

    init?(rawValue: String) {
        if rawValue == "http://test.com/linkOne" {
            self = .linkOne
            return
        } else {
            self = // some regex logic to get the "input" part
            return
        }
        return nil
    }

    typealias RawValue = String
}

Upvotes: 1

Related Questions