FrozenHeart FrozenHeart - 1 month ago 5
Swift Question

What is the more elegant way to remove all characters after specific character in the String object in Swift

What is the more elegant way to remove all characters after specific character in the

String
object in Swift?

Suppose that I have the following string:


str.str


and I need to remove the ".str" from it. How can I do it?

Thanks in advance.

Answer

Here is a way to do it:

var str = "str.str"

if let dotRange = str.rangeOfString(".") {
    str.removeRange(dotRange.startIndex..<str.endIndex)
}

Update In Swift 3 it is:

var str = "str.str"

if let dotRange = str.range(of: ".") {
  str.removeSubrange(dotRange.lowerBound..<str.endIndex)
}