Search code examples
swiftintrospection

How to do introspection in Swift?


I notice properties that aren't defined anywhere in the Swift global definition, such as dynamicType and Type in Any.Type. How do I find out the properties that one can access but aren't documented? Is there a way to do introspection in Swift?


Solution

  • Swift has read only reflection at this point. It's not that great yet, but here's an example of what's available:

    struct Bookmark {
        let title: String, url: String
    }
    
    let bookmark = Bookmark(title: "Stack Overflow", url: "http://stackoverflow.com")
    
    var mirror = reflect(bookmark)
    
    for var propertyNumber = 0; propertyNumber < mirror.count; ++propertyNumber {
        let (propertyName, propertyMirror) = mirror[propertyNumber]
        println("\(propertyName) = \(propertyMirror.summary), \(propertyMirror.count) children")
    }