Created
July 14, 2014 19:21
-
-
Save corvino/0463ef8dcd6bbfcb9c64 to your computer and use it in GitHub Desktop.
Poking at Swift Reflect/Mirror
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func introspectThing(instance: Any) { | |
let mirror = reflect(instance) | |
func findDisposition(mirror : Mirror) -> String { | |
var returnValue = "" | |
switch mirror.disposition { | |
case .Aggregate: | |
returnValue = "Aggregate" | |
case .Class: | |
returnValue = "Class" | |
case .Container: | |
returnValue = "Container" | |
case .Enum: | |
returnValue = "Enum" | |
case .IndexContainer: | |
returnValue = "IndexContainer" | |
case .KeyContainer: | |
returnValue = "KeyContainer" | |
case .MembershipContainer: | |
returnValue = "MembershipContainer" | |
case .Optional: | |
returnValue = "Optional" | |
case .Struct: | |
returnValue = "Struct" | |
case .Tuple: | |
returnValue = "Tuple" | |
} | |
return returnValue | |
} | |
println("Mirror: objectIdentifier = \(mirror.objectIdentifier); mirror.count = \(mirror.count); mirror.summary = \(mirror.summary); mirror.disposition = \(findDisposition(mirror))") | |
for index in 0 ..< mirror.count { | |
let (childKey, childMirror) = mirror[index] | |
println("childKey: \(childKey); childMirror.disposition: \(findDisposition(childMirror))") | |
} | |
} | |
struct ExampleStruct { | |
let x: Int | |
let y: Int | |
var z: Int { | |
get { | |
return 0 | |
} | |
set {} | |
} | |
func doStuff() -> String { | |
return "x: \(x); y: \(y)" | |
} | |
} | |
class ExampleClass { | |
let x: Int | |
let y: Int | |
var z: Int { | |
get { | |
return 0 | |
} | |
set {} | |
} | |
init(x: Int, y: Int) { | |
self.x = x | |
self.y = y | |
} | |
func doStuff() -> String { | |
return "x: \(x); y: \(y)" | |
} | |
} | |
class ExampleObjcClass : NSObject { | |
let x: Int | |
var y: Int | |
var z: Int { | |
get { | |
return 0 | |
} | |
set {} | |
} | |
init(x: Int, y: Int) { | |
self.x = x | |
self.y = y | |
} | |
func doStuff() -> String { | |
return "x: \(x); y: \(y)" | |
} | |
} | |
let exampleStruct : ExampleStruct = ExampleStruct(x: 1, y: 2) | |
let exampleClass = ExampleClass(x: 1, y: 2) | |
let exampleObjcClass = ExampleObjcClass(x: 1, y: 2) | |
println("Test Struct") | |
introspectThing(exampleStruct) | |
println("Test Class") | |
introspectThing(exampleClass) | |
println("Test ObjC Class") | |
introspectThing(exampleObjcClass) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment