2

I want to use reflection to check the property type of a given object at runtime.

I use this code:

//: Playground - noun: a place where people can play import UIKit class Object: NSObject { var type:Int? var name="Apple" var delicious=true } let object = Object() // now check the "type" property println(reflect(object)[1].1.value) // this gives me nil println(reflect(object)[1].1.valueType) // this gives Swift.Optional<Swift.Int> // check for Optional... works fine - Says "Optional" if reflect(object)[1].1.disposition == MirrorDisposition.Optional { println("Optional") } // check for type... does not work, because type is an optional - says: not Int if reflect(object)[1].1.valueType is Int.Type { println("Int") } else { println("no Int") } 

As you can see on this code, I can'n check "valueType", because it is an Optional.

But how can I check the type of this "Optional" property?

Thanks, Urkman

3
  • You know the type of the type property. It is an Int?. What else could you need to know? Commented May 20, 2015 at 15:26
  • Because, this will be generic, so "Object" is just an example. This could be any Object... Commented May 20, 2015 at 15:35
  • Right, but what I mean is, Swift doesn't really want you to do this. It doesn't have real reflection, and this is deliberate. Commented May 20, 2015 at 15:42

1 Answer 1

4

Note that optional Int is a different type from Int so you must check it with Int?.Type

if reflect(object)[1].1.valueType is Int?.Type { println("Int Optional") } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.