0

I have an object defined with about 15 properties. I am trying to iterate over all of the properties that aren't equal to zero and are of type Int or Double. Something like this:

/*
object.price1 = 10.0
object.price2 = 9.9
object.price3 = 8.9
object.price4 = 10.1
object.name = "banana"
object.type = "fruit"
object.quantitySold = 0
object.dateIntroduced = ""
*/

let banana = object()

for property in banana {
    object.property = property*2
}

Any ideas on how to accomplish this?

Collin Bell
  • 334
  • 2
  • 10
  • Should have added something to the example loop that told it to ignore non-numeric properties as well. – Collin Bell Sep 01 '18 at 03:11
  • Possible duplicate of [List of class's properties in swift](https://stackoverflow.com/questions/24844681/list-of-classs-properties-in-swift) – SPatel Sep 01 '18 at 04:25
  • *Maybe* possible if `object` is a reference type deriving from `NSObject`. If `object` is a struct, you are limited to the `Mirror` type which can list but can't manipulate the properties – Code Different Sep 01 '18 at 04:38

2 Answers2

0

Make the prices an array? This is from my phone so check for errors. The bad side to this is how messy it can be and how difficult it would be to keep organized.

 class MyProduct{
 var price1 : Int
 var price2 : Int
 var price3 : Int

  var pricesArray : [Int]

  init(price1 : Int, price2 : Int, price3 : Int, pricesArray : [Int]){
  self.price1 = price1
  self.price2 = price2
  self.price3 = price3


 for i in 0...2
  { pricesArray.append(0)}
  pircesArray[0] = price1
 pricesArray[1] = price2
  pricesArray[2] = price3


self.pricesArray = pricesArray
 }_

 //then to go over it like
    for i in 0...3{
   banana.pricesArray[i] = banana.procesArray[i] * 2
   }

Or you could make a function in the product class

  func equate( sum : Int)
  {
  yourVar = yourVar * sum
  }
Brandon Bravos
  • 390
  • 1
  • 2
  • 10
0

This isn't an easy thing to do in Swift (although possible), but that's no bad thing: being able to iterate over an object's properties and mutate (change) them without having to directly reference a property by name could easily lead to some confusion for you or another developer later on, when you're trying to find out why a property of an object has changed.

Much better instead to make this kind of operation explicit, and name it correctly. Something like the following:

extension Object {
    func doubledPrice() -> Object {
        return Object(
            price1: price1 * 2,
            price2: price2 * 2,
            price3: price3 * 2,
            price4: price4 * 2,
            name: name, //we can't double a string
            type: type,
            quantitySold: quantitySold, //I've named the func assuming you won't double the quantitySold, obviously if that's not the desired behaviour then this needs to change
            dateIntroduced: dateIntroduced //can't double a date
        )
    }
}
sam-w
  • 7,478
  • 1
  • 47
  • 77