Skip to content

Instantly share code, notes, and snippets.

@Daij-Djan
Last active November 14, 2015 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daij-Djan/18e8ab9bcbaa3f073523 to your computer and use it in GitHub Desktop.
Save Daij-Djan/18e8ab9bcbaa3f073523 to your computer and use it in GitHub Desktop.
a helper that uses reflection to get a nsnumber object from from an (optional) Int/Bool/Double/Float property. needed in unit testing
import Foundation
@objc
class ReflectionHelpers : NSObject {
class func getNSNumberForProperty(cls: AnyObject!, name: String!) -> NSNumber! {
let m = Mirror(reflecting: cls)
let child1 = m.descendant(name)
if(child1 != nil) {
//bool
if let b = child1 as? Bool {
return NSNumber(bool: b)
}
if let any = child1, let maybeB = Mirror(reflecting: any).descendant("Some") as? Bool {
if let b = (maybeB as Bool?) {
return NSNumber(bool: b)
}
}
//Int
if let b = child1 as? Int {
return NSNumber(integer: b)
}
if let any = child1, let maybeB = Mirror(reflecting: any).descendant("Some") as? Int {
if let b = (maybeB as Int?) {
return NSNumber(integer: b)
}
}
//Float
if let b = child1 as? Float {
return NSNumber(float: b)
}
if let any = child1, let maybeB = Mirror(reflecting: any).descendant("Some") as? Float {
if let b = (maybeB as Float?) {
return NSNumber(float: b)
}
}
//Double
if let b = child1 as? Double {
return NSNumber(double: b)
}
if let any = child1, let maybeB = Mirror(reflecting: any).descendant("Some") as? Double {
if let b = (maybeB as Double?) {
return NSNumber(double: b)
}
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment