Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic Reflection in Swift.
// Let's define a basic Swift class.
class Fruit {
var type=1
var name="Apple"
var delicious=true
}
// We can get at some info about an instance of an object using reflect(), which returns a Mirror.
reflect(Fruit()).count
reflect(Fruit())[1].0
reflect(Fruit())[1].1.summary
// Dump a bunch of info about the object using reflection.
dump(Fruit())
// Let's make an instance and print all its properties to the console.
var theFruit=Fruit()
for var index=0; index<reflect(theFruit).count; ++index {
println(reflect(theFruit)[index].0 + ": "+reflect(theFruit)[index].1.summary)
}
@mchambers

This comment has been minimized.

Copy link
Owner Author

commented Jun 5, 2014

Note: attempting to "let" the result of reflect() (a Mirror object) into a variable while using the Playground will result in a big "letdown." Get it? Letdown? Heh heh heh... but yeah, it'll fail.

@arish13

This comment has been minimized.

Copy link

commented Jul 2, 2014

Is there a way set the value? I know
reflect(Fruit())[1].1.value = ...
Doesn't work and
theFruit.setValue(..., forKey:reflect(Fruit())[1].0)
Is not reliable

@mitaichik

This comment has been minimized.

Copy link

commented Sep 25, 2014

It real if your object is subclass of NSObject

@philipgeorgiev123

This comment has been minimized.

Copy link

commented Jan 21, 2015

hey i am trying to use reflect on a class that extends View Class like this 😄

class ViewMediator : SKView {

the count of properties is 0, i am looking for a way to make an Automated Injection in Swift

@s4cha

This comment has been minimized.

Copy link

commented May 21, 2015

@philipgeorgiev123 Having the exact same issue here :(

@kheinrich188

This comment has been minimized.

Copy link

commented Jun 16, 2015

Is there a solution for thinks like @arish13 wanted to do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.