Home > OS >  Can we use for loop for items of a struct?
Can we use for loop for items of a struct?

Time:08-03

I have a struct like this:

struct TestType {
    var value1: String? = "1"
    var value2: String? = "2"
    var value3: String? = "3"
    var value4: String? = "4"
    var value5: String? = "5"
    var value6: String? = "6"
    var value7: String? = "7"
    var value8: String? = "8"
    var value9: String? = "9"
}

I want be able to use a for loop on values of TestType, like this code in below, is this possible in swift?

Or even any kind of loop support for items of a struct?

func myTestFunction() {
    let test: TestType = TestType()
    test(value1...value9).forEach { value in
        if let unwrappedValue: String = value {
            print(unwrappedValue)
        }
    }
}

CodePudding user response:

You can use Mirror to achieve that, something like this:

struct TestType {
    var value1: String? = "1"
    var value2: String? = "2"
    var value3: String? = "3"
    var value4: String? = "4"
    var value5: String? = "5"
    var value6: String? = "6"
    var value7: String? = "7"
    var value8: String? = "8"
    var value9: String? = "9"
    
    func iterateThroughProperties() {
        for property in Mirror(reflecting: self).children where property.label != nil {
            print("name: \(property.label!)")
            print("value: \(property.value)")
            print("type: \(type(of: property.value))")
        }
    }
}

CodePudding user response:

[String?](mirrorChildValuesOf: TestType())
public extension Array {
  /// Create an `Array` if `subject's` values are all of one type.
  /// - Note: Useful for converting tuples to `Array`s.
  init?<Subject>(mirrorChildValuesOf subject: Subject) {
    guard let array =
      Mirror(reflecting: subject).children.map(\.value)
      as? Self
    else { return nil }

    self = array
  }
}
  • Related