Structures in swift

having a structure:

struct Person {

var age = 0
var weight = 0
}

How to assign/create an array of Person structure with 10 elements so that one only needs to loop through 10 times and in each iteration update the structure members?.

I am not sure this is what you wanted

let array = Array(repeating: Person(), count: 10)
print(array)
1 Like

Adding to @somu's example:

struct Person : CustomStringConvertible {
    var age = 0
    var weight = 0
    
    var description: String {
        "Person (age: \(age) weight: \(weight))"
    }
}

var persons = Array (repeating: Person(), count: 10)
print (persons)

for i in 0..<persons.count {
    var person = persons [i]
    person.age = i + 20
    person.weight = 10 * i + 50
    persons [i] = person
}
print (persons)

It can be simpler than that…

    var persons: [Person] = (0..<10).map
    {
      .init(age: $0 + 20, weight: 10 * $0 + 50)
    }
    
    print (persons)
3 Likes

Note that you don't need to create an Array to use map; because it's defined on Sequence, to which Range conforms, you can simply write (0..<10).map {

1 Like

Thanks Steve

I'm sure that failed to compile when I first tried it - works fine now.

At this rate of removing superfluous code we'll only have to think of an algorithm for it to work :stuck_out_tongue_winking_eye:

I've altered the code in my post

Usually when that happens it's because one has omitted the parentheses: 0..<10.map will not work, because would have to parse as 0..<(10.map).

3 Likes

Moving on, you could also do something cunning to update persons, like…

// add an extension to Array for Person elements

extension Array where Element == Person
{
  mutating func update(_ params: (index: Int, age: Int, weight: Int)...)
  {
    params.forEach
    {
      self[$0.index] = .ini(t(age: $0.age, weight: $0.weight)
    }
  }
}

    {
      …
      
      persons.update((index: 1, age: 21, weight: 165), (index: 5, age: 42, weight: 234))
    }