ios - 如何创建带参数的枚举?

标签 ios swift enums

这是我的枚举

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

它在我的大多数情况下都运行良好。但是,我现在想创建另一个将采用参数的链接,它看起来像这样

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

有没有一种方法可以将字符串参数添加到我的枚举案例之一,以便我可以为 linkTwo 提供类似的东西

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

非常感谢!

最佳答案

您不能将原始值添加到具有关联值的枚举中。但是,您可以将属性和方法添加到您的枚举中,这样您就可以执行如下操作:

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"
        }
    }
}

你也可以符合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
}

关于ios - 如何创建带参数的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50776713/

相关文章:

ios - (SIGABRT尝试使用未知的类项目名称)EXC_BAD_ACCESS错误在Xcode 11,Swift 5,iOS 13中的强引用变量上

ios - 如何防止 EVURLCache 缓存带有 Cache-Control header 的请求?

c# - 通用方法和无效上下文异常

android - 如何将枚举值传递给 wcf webservice

ios - 带有参数的 Swift 类型反射初始化

ios - 多个 Controller 的快速通知

ios - 在解析 JSON 时使用 NSDictionary 有什么优势或好处?

ios - swift AVAudioEngine 崩溃 : player started when in a disconnected state

c - 使用 C 进行数字到字符串的映射

iOS:VoiceOver 在错误的位置点击