Adam Bardon
Adam Bardon

Reputation: 3909

Accessing enum values in struct with if statement

Having struct like this:

struct ScrollTableViewColumn {
    var ContentType: ContentType

    enum ContentType {
        case String
        case Numeric(sum: Double, width: CGFloat)
    }
}

I can access the numbers stored in content type with switch statement like this:

switch column.ContentType {
case .Numeric(let sum, let width):
   // do something with sum and width…

How can I achieve similar thing with if statement?

Upvotes: 0

Views: 399

Answers (1)

Nirav D
Nirav D

Reputation: 72460

First of all you need to make property names and enum values with a lowercase, so change your enum like this.

enum ContentType {
    case string
    case numeric(sum: Double, width: CGFloat)
}

Now you can use if case this way.

if case .numeric(let sum, let width) = column.ContentType {
     print(sum, width)
}

Edit: You can also make if case like this way.

if case let .numeric(sum, width) = column.ContentType {
     print(sum, width)
}

Upvotes: 2

Related Questions