我试图在枚举中执行一个函数,但当执行此代码ContentType.SaveContent("News")
时,我不断收到以下错误:Use of instance member on type 'ContentType'; did you mean to use a value of type 'ContentType' instead?
。当我将类型设置为String时,为什么它不运行?
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
}
}
}
我可能会这样做,而不是你想要做的:在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()
}
它不是static func
,因此您只能将它应用于类型的实例,而不能应用于类型本身,这正是您想要做的。在func
之前添加static
。
而且,为了保持良好的风格,不要给func
的大写字母。。。