Prashant Rastogi
Prashant Rastogi

Reputation: 21

Can We have initializers in Enum in Swift?

I'm try to play with swift and enum. My concern is that Enum in swift is the Value data type. So can we have initializers in this like structure or class.

Upvotes: 1

Views: 173

Answers (1)

0x416e746f6e
0x416e746f6e

Reputation: 10136

Yes, we can:

enum Foo {
    case Bar, Qux

    init?(_ string: String) {
        switch string {
        case "Bar":
            self = .Bar
        case "Qux":
            self = .Qux
        default:
            return nil
        }
    }    
}

let foo = Foo("Bar")!

print(foo) // prints "Bar"

Upvotes: 2

Related Questions