In Swift 4, use upperBound
and subscript operators and open range:
let snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"
if let range = snippet.range(of: "Phone: ") {
let phone = snippet[range.upperBound...]
print(phone) // prints "123.456.7891"
}
Or consider trimming the whitespace:
if let range = snippet.range(of: "Phone:") {
let phone = snippet[range.upperBound...].trimmingCharacters(in: .whitespaces)
print(phone) // prints "123.456.7891"
}
By the way, if you're trying to grab both at the same time, a regular expression can do that. E.g., in iOS 16 and later:
let snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"
if let match = snippet.firstMatch(of: /^(.*?)\s*Phone:\s*(.*)$/.ignoresCase()) {
let address = match.output.1
let phone = match.output.2
}
Or in earlier iOS versions, we might use NSRegularExpression
:
let snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"
let regex = try! NSRegularExpression(pattern: #"^(.*?)\s*Phone:\s*(.*)$"#, options: .caseInsensitive)
if let match = regex.firstMatch(in: snippet, range: NSRange(snippet.startIndex..., in: snippet)) {
let address = snippet[Range(match.range(at: 1), in: snippet)!]
let phone = snippet[Range(match.range(at: 2), in: snippet)!]
}
For prior versions of Swift, see previous revision of this answer.