title: Swift Reflection Type Checking
body: <p>I'm currently experimenting with Swift reflection and subscripting. In my class, I have the following function to check whether a given key/variable exists:</p>
  
  <pre><code>func getMirror(key: String) -&gt; MirrorType? {
      let mirror = reflect(self)
      for i in 0..&lt;mirror.count {
          let (name,type) = mirror[i]
          if name == key { return type }
      }
      return nil 
  }
  </code></pre>
  
  <p>Then, in the subscript declaration, I do the following:</p>
  
  <pre><code>subscript(key: String) -&gt; AnyObject? {
     ...
     set(newValue) {
          if let mirror : MirrorType = getMirror(key) {
              var type : Any.Type = mirror.valueType
              // Check here whether newValue is castable as type
          }
     }
  }
  </code></pre>
  
  <p>The question is now whether there's a possibility to check if newValue can be safely set for the respective variable via</p>
  
  <pre><code>self.setValue(newValue, forKey: key)
  </code></pre>
  
  <p>which returns an exception if the value is not settable. If a have a Swift.Int or Swift.Double variable</p>
  
  <pre><code>println(type)
  </code></pre>
  
  <p>or</p>
  
  <pre><code>toString(type)
  </code></pre>
  
  <p>gives me exactly these names of the types. But is there a way to probe casting of newValue to these types? I can't directly compare strings because </p>
  
  <pre><code>newValue.dynamicType
  </code></pre>
  
  <p>returns Swift.Optional or __NSCFNumber for instance if unwrapped. I've tried with NSClassFromString, but it doesn't seem to work with Swift native types. Is there a way to do this?</p>
  
  <p>Thanks!</p>
  
  <p>Edit: </p>
  
  <p>One thing in additional: I've also tried the following </p>
  
  <pre><code>if let convertedValue: AnyObject = mirror.value as? AnyObject {
      var type = convertedValue.dynamicType
  }
  </code></pre>
  
  <p>and then I could for instance use </p>
  
  <pre><code>newValue!.isKindOfClass(type)
  </code></pre>
  
  <p>However, if I have an optional in the class which is not yet instantiated, this doesn't work, as mirror.value is nil. Also, newValue might still be convertable to the required type. </p>