这是我的枚举
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/