title: In Swift, how can I use setValueForKey to set the textAlignment property of an object?
body: <p>Let's say we define an object like this:</p>
  
  <pre><code>let object: AnyObject = {
  
      var result = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 50))
      result.text = "First Text"
      result.backgroundColor = UIColor.blueColor()
  
      return result
  }()
  </code></pre>
  
  <p>For this example, I explicitly created a <code>UILabel</code>, but in my actual project I don't know what type of object is created, so I'm just treating the result as <code>AnyObject</code> for this example. The object is just a standard UILabel with text of "First Text" on a blue background, default aligned to the left.</p>
  
  <p>In this example case, I know that this object is actually a <code>UILabel</code>, so I know I can change it's properties like this:</p>
  
  <pre><code>(object as UILabel).text = "Second Text"
  </code></pre>
  
  <p>And now I've changed the text. But in my actual project, I don't know that my object is a <code>UILabel</code>, so I can't just do the <code>(object as UILabel)</code> trick, because it's not always a <code>UILabel</code>. My way around that is using <code>setValueForKey</code>. After checking that my object has a member called "text" using <code>respondsToSelector</code> (not shown in this example), I can change the text this way:</p>
  
  <pre><code>object.setValue("Third Text", forKey: "text")
  </code></pre>
  
  <p>Now, if I wanted to change the <code>textAlignment</code> of the object, after checking that the object does indeed have a member called <code>textAlignment</code>, I'd want to do something like this:</p>
  
  <pre><code>object.setValue(NSTextAlignment.Center, forKey: "textAlignment")
  </code></pre>
  
  <p>Doing this results in an error though:</p>
  
  <pre><code>Type 'NSTextAlignment' does not conform to protocol 'AnyObject'
  </code></pre>
  
  <p>I ran into something similar while trying this approach with setting the <code>frame</code>, because it didn't like the <code>CGRect</code> type, but I was able to get around it by converting the <code>CGRect</code> to an <code>NSValue</code>. However, I can't find a way to fix it for <code>enum</code> types like <code>NSTextAlignment</code>.</p>
  
  <p>Anybody know how I can achieve my goal here?</p>