A C
A C

Reputation: 729

How to return array of different enums based on a condition in Swift?

I have two enum declarations enum A and enum B. I would like to know if it's possible to assign the value of the static member allValues to a property, or use it as a return value of a function like getEnumValuesBasedOnCondition. If it's possible, how could it be done?

I tried setting the return type to be [AnyObject] but that doesn't work.

Thanks.

enum A {
  case x
  case y
  case z

  static let allValues = [x,y,z] 
}

enum B {
  case t
  case u
  case v

  static let allValues = [t,u,v]
}

 func getEnumValuesBasedOnCondition(condition: Bool) -> [] {
    if condition {
       return A.allValues
    } else {
       return B.allValues
    }
 }

Upvotes: 1

Views: 733

Answers (1)

Pradeep K
Pradeep K

Reputation: 3661

You can define a new Enum type and use associated values for this.

enum A {
    case x
    case y
    case z

    static let allValues = [x,y,z]
}

enum B {
    case t
    case u
    case v

    static let allValues = [t,u,v]
}

enum AorB {
    case aValues(values:[A])
    case bValues(values:[B])
}

func getEnumValuesBasedOnCondition(condition: Bool) -> AorB {
    if condition {
        return AorB.aValues(values:A.allValues)
    } else {
        return AorB.bValues(values:B.allValues)
    }
}

let valA:AorB = getEnumValuesBasedOnCondition(true)
let valB:AorB = getEnumValuesBasedOnCondition(false)

You can determine which allValues are contained by using this

let val:AorB = getEnumValuesBasedOnCondition(<trueOrFalse>)
switch val {
case .aValues(let v):
    print ("val contains allValues of A and values are \(v)")
case .bValues(let v):
    print ("val contains allValues of B and values are \(v)")
}

Upvotes: 1

Related Questions