0

I want to create structure with method inside it, with a switch statement that switches on the instance's property, and appends self to the proper array.

Trying this, but it's wrong:

struct Workout {
    enum Stroke {
        case freestyle, butterfly
    }
    var distance : Double
    var time: Double
    var stroke: Stroke
    var freestyleArray : [Workout] = []
    var butterflyArray : [Workout] = []

    mutating func saveToArray () {
        switch stroke {
        case .freestyle : freestyleArray.append(self)
        case .butterfly : butterflyArray.append(self)
        }
    }
}
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Mak
  • 9
  • 4
  • why is this wrong? – JuicyFruit Nov 21 '17 at 07:40
  • Although appending to an array within a struct of the same type of that struct seems kind of weird to me, I tried your code and it *does* work fine for me, what's "but it's wrong" you facing? – Ahmad F Nov 21 '17 at 07:48

1 Answers1

0

What you're doing is technically totally fine. You know that struct is passed by copying. Therefore, no problem if you pass self in a mutating func, since whenever you do it, you are passing a copy of a struct, which leads to mutation and re-creation of initial struct with that appended instance/copy in.

struct Workout {
    enum Stroke {
        case freestyle, butterfly
    }
    var distance : Double
    var time: Double
    var stroke: Stroke
    var freestyleArray : [Workout] = []
    var butterflyArray : [Workout] = []

    mutating func saveToArray () {
        switch stroke {
        case .freestyle : freestyleArray.append(self)
        case .butterfly : butterflyArray.append(self)
        }
    }
}

var wo = Workout(distance: 10,
                 time: 10,
                 stroke: .butterfly,
                 freestyleArray: [],
                 butterflyArray: [])

wo.saveToArray()
wo.saveToArray()

// prints 2
print("butterfly array count: \(wo.butterflyArray.count)")

However, if this is precisely your problem - multiplication of semantically same instances, - then you should definitely use class instead of struct. This way you will be able to compare instances of a class by reference (before appending, if that's the concern). To compare structs , you'd have to introduce identifier for distinction.

Hexfire
  • 5,945
  • 8
  • 32
  • 42