0

I have an array of structs that has been decoded from a JSON file. Each struct has a stored property that is a variable-dimension array stored in an enum associated value.

Some of the structs have property Enum.array2D([[Float]]) and others have Enum.array3D([[[Float]]])

Is there a simple or elegant way to extract a variable-type associated value from the struct's enum property - maybe with a getter function? Currently, the only way I know how to do this is with an external switch anytime I want to access the underlaying value. For example, somewhere in external code I have to use this anytime I want to get these values and manipulate them:

switch structArray[index].enumProperty {

case .array2D(let array2Val):
    // Do stuff with the 2D array
case .array3D(let array3Val):
    // Do stuff with the 3D array
}

I have considered adding each of the two possible types as optionals and setting the correct one in the init function with a switch, but that seems inefficient as I’ll have the arrays stored in two places.

whaleshark
  • 65
  • 6
  • Are there any similarities between the things you do with the 2D array, and the things you do with the 3D array? if not, a switch statement is just fine, isn't it? – Sweeper Oct 06 '22 at 18:15
  • @Sweeper I suppose there’s nothing wrong with it. Maybe that’s what I should do- I just didn’t know if there were better practices. The processing is similar - I’m just repeating the 2D array processing on the 3D array for each index. – whaleshark Oct 06 '22 at 18:23
  • If the processing is the same, and it's just the looping that's different, you can probably add a method to the enum to avoid the switch statement. If you show more of the code, I might be able to post an answer. Show the enum, and show the similarity of the switch cases. – Sweeper Oct 06 '22 at 18:27

0 Answers0