いまさらですが、 NSTextCheckingResult
に range(withName:)
なる定義が追加されていたので試してみました。
func yearMonthDay(from target: String) -> (year: Int, month: Int, day: Int)? {
let pattern = "(?<year>\\d+)-(?<month>\\d+)-(?<day>\\d+)"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let nsTarget = target as NSString
let nsRange = NSRange(location: 0, length: nsTarget.length)
guard let result = regex.firstMatch(in: target, options: [], range: nsRange) else {
return nil
}
return (
Int(nsTarget.substring(with: result.range(withName: "year")))!,
Int(nsTarget.substring(with: result.range(withName: "month")))!,
Int(nsTarget.substring(with: result.range(withName: "day")))!
)
}
print(yearMonthDay(from: "2018-4-10"))
// Optional((year: 2018, month: 4, day: 10))