title: Access a struct property by its name as a string in Swift
body: <p>Let's say I have the following <code>struct</code> in <code>Swift</code>:</p>
  
  <pre><code>struct Data {
     let old: Double
     let new: Double
  }
  </code></pre>
  
  <p>Now I have a class with an array of Data structs:</p>
  
  <pre><code>class MyClass {
     var myDataArray: [Data]
  }
  </code></pre>
  
  <p>Now let's say I want to calculate the average of either the old or the new values:</p>
  
  <pre><code>func calculateAverage(oldOrNew: String) -&gt; Double {
     var total = 0.0
     count = 0
  
     for data in myDataArray {
        total += data.oldOrNew
        count++
     }
  
     return total / Double(count)
  }
  </code></pre>
  
  <p>And then:</p>
  
  <pre><code>let oldAverage = calculateAverage("old")
  let newAverage = calculateAverage("new")
  </code></pre>
  
  <p>But this obviously doesn't work, since <code>oldOrNew</code> is not a member of my <code>struct</code>.</p>
  
  <p>How can I access <code>old</code> or <code>new</code> from <code>"old"</code> or <code>"new"</code> ?</p>