Created
February 12, 2017 18:54
-
-
Save andrevidela/b2ac9bfe63e55bd25877719353a7407a to your computer and use it in GitHub Desktop.
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
func parse(source: String) -> Person? { | |
func startingIndex(`for` string: String, after offset: Int) -> String.Index { | |
return string.index(string.startIndex, offsetBy: offset) | |
} | |
let lines = source.components(separatedBy: "\n") | |
guard lines.count >= 4 else { return nil } | |
var age: Int? = nil | |
if lines[1].hasPrefix("age: ") { | |
let start = startingIndex(for: lines[1], after: 5) | |
age = Int(lines[1][start...start]) | |
} | |
var name: String? = nil | |
if lines[2].hasPrefix("name: ") { | |
name = lines[3].substring(from: startingIndex(for: lines[3], after: 6)) | |
} | |
var city: String? = nil | |
if lines[3].hasPrefix("city: ") { | |
city = lines[3].substring(from: startingIndex(for: lines[3], after: 6)) | |
} | |
if let a = age, let n = name, let c = city { | |
return Person(name: n, age: a, city: c) | |
} else { | |
return nil | |
} | |
} | |
let parsedPerson = parse(source: source) | |
print(parsedPerson ?? "not parsed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment