Created
May 21, 2015 19:14
-
-
Save robtimp/9aea4d3943f032ca4178 to your computer and use it in GitHub Desktop.
String Parsing (objc.io #9) in Swift - Example 2
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
// objc.io Issue #9 | |
// February, 2014 | |
// String Parsing by Chris Eidhof | |
// | |
// Example 2 | |
// Swift version by Rob Hudson | |
import UIKit | |
let FormatError = 100 | |
let MyErrorDomain = "io.objc.parsing" | |
let input: NSString = "backgroundColor = #ff0000\ntextColor = #0000ff" | |
func parse(input: NSString, inout error: NSError?) -> [String : String]? { | |
let pattern = "(\\w+) = #([\\da-f]{6})" | |
let expression = NSRegularExpression(pattern: pattern, options: nil, error: nil) | |
let lines = input.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as! [NSString] | |
var result = [String : String]() | |
for line in lines { | |
if let textCheckingResult = expression?.firstMatchInString(line as String, options: nil, range: NSMakeRange(0, line.length)) { | |
let key = line.substringWithRange(textCheckingResult.rangeAtIndex(1)) | |
let value = line.substringWithRange(textCheckingResult.rangeAtIndex(2)) | |
result[key] = value | |
} else { | |
let message = "Couldn't parse line: \(line)" | |
let errorDetail = [NSLocalizedDescriptionKey : message] | |
error = NSError(domain: MyErrorDomain, code: FormatError, userInfo: errorDetail) | |
return nil | |
} | |
} | |
return result | |
} | |
var error: NSError? | |
if let output = parse(input, &error) { | |
println(output) | |
} else { | |
println(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment