在枚举情况下添加参数。收到错误:'Enum with raw type cannot have cases with arguments'



我想做这样的事情:

public enum MyEnum: String {
case tapOnSection(section: String) = "tap on (section)"
}

var section: String = "funny section"
func someFuntion() {
print(MyEnum.tapOnSection(self.section))
}

控制台:"点击有趣的部分">

如果我能做这样的事情或一些建议,你会吗?

谢谢

您可以将方法添加到enums

public enum MyEnum {
case tapOnSection(section: String)
var description: String {
switch self {
case let tapOnSection(section: section):
return "tap on (section)"
}
}
} 

var funnySection: String = "funny section"
print(MyEnum.tapOnSection(funnySection).description)

enum不能同时具有关联的值(即带有参数的情况(和原始值。这是目前语言的限制。

我能想到的近似您想要的最简单的方法是创建一个以某种方式替换原始值的计算属性。 例如,对于您的具体情况,您可以这样做:

enum MyEnum
{
case tapOnSection(section: String)
} 
// Might as well implement CustomStringConvertible so you  can do
// print(MyEnum.something) instead of print(MyEnum.something.description)
extension MyEnum: CustomStringConvertible 
{
var description: String 
{
switch self 
{
case .tapOnSection(let section):
return "tap on (section)"
// A switch case for each case in your enum
}
}
}
print(MyEnum.tapOnSection(section: "foo")) // prints "tap on foo"

最新更新