Wow. Swift makes it really fiddly to copy a substring from a simple String.
Most programming languages allow characters to be simply indexed by their intege
You can use
let ind1 = str.startIndex.advancedBy(c1, limit: str.endIndex)
let ind2 = str.startIndex.advancedBy(c1+c2, limit: str.endIndex)
to advance the start index by the given amounts, but not beyond the end index of the string. With that modification, your function gives
subStr ("Stack Overflow", c1: 6, c2: 12) // "Overflow"
subStr ("Stack Overflow", c1: 12, c2: 20) // ""
I quickly made a nice substring function for String
s without Foundation dependency:
extension String {
func substring(from: Int, length: Int) -> String {
return String(dropFirst(from).prefix(length))
}
}
If the length is bigger than possible, it just gives all the characters to the end. Can't crash Can't crash as long as neither argument is negative (it makes sense to crash if any argument is negative since that would be a major flaw in your code).
Example usage:
"Stack Overflow".substring(from: 6, length: 12)
gives
"Overflow"