Peter Pik Peter Pik - 6 months ago 37
Swift Question

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

}

Answer

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