ios – 在枚举中执行函数

我正在尝试在枚举中执行一个函数,但是当执行此代码时,ContentType.SaveContent(“新闻”)我不断收到以下错误:在类型’ContentType’上使用实例成员;你的意思是使用’ContentType’类型的值吗?当我将类型设置为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()
}
点赞