Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/108.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在枚举内执行函数_Ios_Swift_Enums - Fatal编程技术网

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()
}