Created
August 14, 2015 19:45
-
-
Save jkopelioff/263af2b882962542acf6 to your computer and use it in GitHub Desktop.
A function equivalent to "valueForKeyPath" but supports Array substructure
This file contains hidden or 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
| public extension NSObject { | |
| func valueForKeyPathWithIndexes(fullPath:String) -> AnyObject? { | |
| var testrange:NSRange = (fullPath as NSString).rangeOfString("[") | |
| if testrange.location == NSNotFound { | |
| return self.valueForKeyPath(fullPath) | |
| } | |
| let parts:Array = fullPath.componentsSeparatedByString(".") | |
| var currentObj:AnyObject? = self | |
| for part:String in parts { | |
| let range1:NSRange = (part as NSString).rangeOfString("[") | |
| if range1.location == NSNotFound { | |
| currentObj = currentObj?.valueForKey(part) | |
| } | |
| else | |
| { | |
| var arrayKey:String = (part as NSString).substringToIndex(range1.location) | |
| if let index = ((part as NSString).substringToIndex(count(part)-1) as NSString).substringFromIndex(range1.location+1).toInt(), | |
| let array = currentObj?.valueForKey(arrayKey) as? NSArray { | |
| currentObj = array.objectAtIndex(index) | |
| } | |
| } | |
| } | |
| return currentObj | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment