P.Festus
P.Festus

Reputation: 95

Swift closure to iterate over a class object

Curious to know if anyone has a swift closure solution to transform the following for/in loop iteration over an array containing multiple class objects? The class is composed of two properties of type string. A class function instantiates multiple objects and places them into an array. In the example below, the array nhSearchObject has 10 indices containing 10 objects of the class.

class President{
   var firstName:String 
   var lastName:String
    init(...)
    }       
  // class function creates objects and places them into an array   nhSearchObject

for i in nhSearchObject[0...6] {
    i.firstName = "George"
    i.lastName = "Washington"
}

It is imperative to preserve the subscript range feature as I only want to change the indices 0...6. Also, I do not want to create a new array. Simply interested in iterating over the array slice 0..6 of the 10 indices of the existing array to modify object properties.

Upvotes: 1

Views: 667

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59526

First of all your class is President (no Presidents)

class President {
    var firstName:String
    var lastName:String
    init(firstName: String, lastName:String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

Now given the following array

let presidents: [President] = ...

you can follow 2 approaches

If you are sure the array has at least 7 elements then

presidents[0...6].forEach { president in
    president.firstName = "George"
    president.lastName = "Washington"
}

Otherwise

presidents
    .enumerated()
    .filter { $0.offset <= 6 }
    .forEach { elm in
        elm.element.firstName = "George"
        elm.element.lastName = "Washington"
    }

Upvotes: 2

Niels Snakenborg
Niels Snakenborg

Reputation: 74

nhSearchObject.forEach { $0.firstName = "George"; $0.lastName = "Washington" }

Upvotes: -1

Related Questions