How do I substring a string in swift 4.
I would like to convert:
"Hello, World!"
Into:
"Hello"
Swift has no built in function to make this easy so I wrote a simple extension to get the same functionality as other languages such as python which have really easy substring functions.
Extension
Outside your class, add this extension for strings.
extension String { func substring(start: Int, range: Int) -> String { let characterArray = Array(self) var tempArray:[Character] = [] let starting = start let ending = start + range for i in (starting...ending) { tempArray.append(characterArray[i]) } let finalString = String(tempArray) return finalString } } Usage
let myString = "Hello, World!" print(myString.substring(start: 0, range: 4)) This prints:
"Hello"
How It Works
The extension works by turning the string into an array of separate characters then creates a loop which appends the desired characters into a new string which is determined by the function's parameters.
Thanks for stopping by. I hope apple add this basic functionality to their language soon! The above code is a bit messy so if anyone wants to clean it up then feel free!