-1

How can I make a swift struct return another struct based on a switch statement? I need it to work like the so: if the time is afternoon then MainStruct will return StructA, and if the time is morning, MainStruct will return StructB. I tried implementing it like this:

struct MainStruct {
    switch(time) {
    case .morning:
        return StructB
    case .afternoon:
        return StructA
    }
}

but I get this error on the switch statement: "Expected declaration".

Andrew
  • 25
  • 3

1 Answers1

2

There's a number of problems with your example:

  1. a struct cannot return value - you'll need a method (or computed property) for this.
  2. you're referencing an undefined enum time that comes from nowhere, so it's not possible to tell if the switch is exhaustive.
  3. you need to return an instance of a type, not just the type name.
  4. you are returning two different types, which would only work if they both conform to, and you return, the same protocol, or if you change them to classes and return a parent class.

The contrived example below tries to demonstrate these concepts, which may help you research them, although I'm not sure of its utility!

protocol MyProtocol {
  // protocol definition
}

struct StructA: MyProtocol {
  // struct contents and protocol conformance
}

struct StructB: MyProtocol {
  // struct contents and protocol conformance
}


struct MainStruct {
   enum TimePeriod {
       case morning
       case afternoon
   }

   func structFor(timePeriod time: TimePeriod) -> MyProtocol {
      switch(time) {
      case .morning:
        return StructB()
      case .afternoon:
        return StructA()
    }
}
flanker
  • 3,840
  • 1
  • 12
  • 20