Peter Pik
Peter Pik

Reputation: 11193

execute function inside enum

I'm trying to execute a function inside an enum, but when execute this code ContentType.SaveContent("News") i keep getting following error: Use of instance member on type 'ContentType'; did you mean to use a value of type 'ContentType' instead?. Why wont it run when i've set the type to 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
        }
    }

}

Upvotes: 4

Views: 1460

Answers (2)

fred foc
fred foc

Reputation: 221

I would probably do this instead of what you are trying to do : in ContentType Enum a func :

func saveContent() {
    switch self {
    case .News:
        print("news")
    case .Card:
        print("cards")
    }
}

in the other part of code that will use your enum :

func saveContentInClass(type: String) {
    guard let contentType = ContentType(rawValue: type) else {
        return
    }
    contentType.saveContent()
}

Upvotes: 1

Grimxn
Grimxn

Reputation: 22487

It's not a static func, therefore you can only apply it to an instance of the type, not to the type itself, which is what you are trying to do. Add static before func.

...and, just for good style, don't give funcs capital letters...

Upvotes: 1

Related Questions