Ios 在枚举内执行函数
我试图在枚举内执行一个函数,但当执行此代码Ios 在枚举内执行函数,ios,swift,enums,Ios,Swift,Enums,我试图在枚举内执行一个函数,但当执行此代码ContentType.SaveContent(“News”)时,我不断遇到以下错误:在类型“ContentType”上使用实例成员;您的意思是使用“ContentType”类型的值吗?。当我将类型设置为字符串时,为什么它不运行 enum ContentType: String { case News = "News" case Card = "CardStack" func SaveContent(type: String)
ContentType.SaveContent(“News”)
时,我不断遇到以下错误:在类型“ContentType”上使用实例成员;您的意思是使用“ContentType”类型的值吗?
。当我将类型设置为字符串时,为什么它不运行
enum ContentType: String {
case News = "News"
case Card = "CardStack"
func SaveContent(type: String) {
switch type {
case ContentType.News.rawValue:
print("news")
case ContentType.Card.rawValue:
print("card")
default:
break
}
}
}
它不是一个
静态函数
,因此您只能将其应用于类型的实例,而不能应用于类型本身,这正是您尝试执行的操作。在func
之前添加static
…而且,为了保持良好的风格,不要用大写字母表示
func
s…我可能会这样做,而不是你想做的:
在ContentType枚举函数中:
func saveContent() {
switch self {
case .News:
print("news")
case .Card:
print("cards")
}
}
在将使用枚举的代码的另一部分中:
func saveContentInClass(type: String) {
guard let contentType = ContentType(rawValue: type) else {
return
}
contentType.saveContent()
}