Search code examples
swiftstringsubstring

How to get first n characters from variable string length in Swift


I have a string of variable length, but always containing lets say XXX at the end. How can I get the string from the start to the XXX - so without the XXX? It would be easy in python since it uses Int as string indexes, but Swift doesn't do that. How can I achieve the same result in Swift?

Python code example:

code = "ABCDEFGXXX"

text = code[:-3]

so text is equal to "ABCDEFG"


Solution

  • Without knowing python I think dropLast most resembles the python example you provided

    code.dropLast(3)