What is the way of extracting last word in a String in Swift? So if I have \"Lorem ipsum dolor sit amet\", return \"amet\". What is the most efficient way of doing this?
The other answers are fine if you want to include Foundation classes. If you want to use Swift-only classes then you can do it this way:
One way to do it is to use indices. This is probably the fastest way with long strings:
Swift 4:
let str = "Lorem ipsum dolor sit amet"
let size = str.reversed().firstIndex(of: " ") ?? str.count
let startWord = str.index(str.endIndex, offsetBy: -size)
let last = str[startWord...] // -> "amet"
Or you could split the string:
Swift 4:
let str = "Lorem ipsum dolor sit amet"
let split = str.split(separator: " ")
let last = String(split.suffix(1).joined(separator: [" "]))
let lastTwo = String(split.suffix(2).joined(separator: [" "]))
print(last) // -> "amet"
print(lastTwo) // -> "sit amet”
Swift 3:
let str = "Lorem ipsum dolor sit amet"
let split = str.characters.split(separator: " ")
let last = String(split.suffix(1).joined(separator: [" "]))
let lastTwo = String(split.suffix(2).joined(separator: [" "]))
print(last) // -> "amet"
print(lastTwo) // -> "sit amet”
Swift 2:
let str = "Lorem ipsum dolor sit amet"
let split = str.characters.split(Character(" "))
let last = String(split.suffix(1).joinWithSeparator([" "]))
let lastTwo = String(split.suffix(2).joinWithSeparator([" "]))
print(last) // -> "amet"
print(lastTwo) // -> "sit amet"