[Pitch] Reflection

I'm really excited about more introspection capabilities in the language, but after reading the proposal, I think it's missing an important feature, and I don't quite understand another.

What I really want to do is be able to find all types in a module (or linked into the app) that conform to a given protocol, and then instantiate instances of those. Example (forgive me playing fast and loose with Swift syntax):

protocol ImageFilterPlugin {
	init(param1: Float, param2: Float)
    func process(image: Image) -> Image
}

…

struct MyImageFilterPlugin : ImageFilterPlugin {
    
    init(param1: Float, param2: Float) {
    }
    
    func process(image: Image) -> Image {
        <process and return an image>
    }
}

…

func
instantiateImageFilter(filterNamed: String)
	-> ImageFilterPlugin
{
	let filterType = Reflection.type<ImageFilterPlugin>(named: "MyImageFilterPlugin")
	let filter = filterType(param1: x, param2: y)
	return filter
}

func
listImageFilters()
{
	for filterType in Reflection.types(conformingTo: ImageFilterType.self) {
		print("Filter: \(filterType.name)")
	}
}

It would be even better if I could iterate over all the methods of a type, find the initializers, and choose one to call. Even better would be a way to annotate things to make them findable (the way Java does). I could annotate any type, property, method, function parameter, and act based on those annotations (search for, construct a call to, etc.).

The thing I'm not clear on in your examples: They show (e.g.) instantiating Types, but it's not clear to me how to instantiate an instance of that type.

8 Likes