【问题标题】:execute function inside enum在枚举中执行函数
【发布时间】:2016-05-09 08:36:04
【问题描述】:

我正在尝试在枚举中执行一个函数,但是当执行此代码 ContentType.SaveContent("News") 时,我不断收到以下错误:Use of instance member on type 'ContentType'; did you mean to use a value of type 'ContentType' instead?。为什么我将类型设置为字符串时它不会运行?

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

}

【问题讨论】:

    标签: ios swift enums


    【解决方案1】:

    我可能会这样做而不是你想要做的事情: 在 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()
    }
    

    【讨论】:

      【解决方案2】:

      它不是static func,因此您只能将其应用于类型的实例,而不是类型本身,这正是您想要做的。在func 之前添加static

      ...而且,为了更好的风格,不要给funcs 大写字母...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-30
        • 2011-08-20
        • 2011-07-03
        • 1970-01-01
        • 2015-04-02
        • 1970-01-01
        • 2012-02-16
        相关资源
        最近更新 更多