Is it possible to put a tuple in an enum using Swift?

If I have the following enum:

enum FruitTuple
{
    static let Apple = (shape:"round",colour:"red")
    static let Orange = (shape:"round",colour:"orange")
    static let Banana = (shape:"long",colour:"yellow")
}

      

Then I have the following function:

static func PrintFruit(fruit:FruitTuple)
{
    let shape:String = fruit.shape
    let colour:String = fruit.colour

    print("Fruit is \(shape) and \(colour)")
}

      

Q fruit.shape

and fruit.colour

I get the error:

Value of type 'FruitTuple' has no member 'shape'

Honest enough, so I modify the enum to be of type:

enum FruitTuple:(shape:String, colour:String)
{
    static let Apple = (shape:"round",colour:"red")
    static let Orange = (shape:"round",colour:"orange")
    static let Banana = (shape:"long",colour:"yellow")
}

      

But then in the enum declaration I get the error:

Inheritance from non-named type '(shape: String, colour: String)'

So the question is, is it possible to have a tuple in an enum and be able to refer to its constituent parts in this way? Am I just missing something fundamental here?

+3


source to share


1 answer


As @MartinR pointed out. In addition, according to Apple docs, "enumeration cases can specify associated values โ€‹โ€‹of any type to be stored along with each value of each case." If you want to keep using enum

, you might need to do something like:

static func PrintFruit(fruit:FruitTuple.Apple)
{
    let shape:String = fruit.shape
    let colour:String = fruit.colour

    print("Fruit is \(shape) and \(colour)")
}

      



I'm not sure what you want, but I think using typealias

might help you achieve your goal.

typealias FruitTuple = (shape: String, colour: String)

enum Fruit
{
    static let apple = FruitTuple("round" , "red")
    static let orange = FruitTuple("round", "orange")
    static let banana = FruitTuple("long", "yellow")
}

func printFruit(fruitTuple: FruitTuple)
{
    let shape:String = fruitTuple.shape
    let colour:String = fruitTuple.colour
}

      

+4


source







All Articles