A simpler Swift substring

As a Swift beginner, substrings are complex. For an app I was developing, I only needed “simple” substrings as found in JavaScript, C#, SQL, and other languages. I know the data that is expected, and the complexity of Swift’s substring process is unnecessary.

This substring extension works on the pattern of starting position beginning at 1 (one) for the first character in the string, and the length to extract, including the starting position. If the length exceeds the string length, the remainder of the string from the starting position is returned.

Usage:

let mystring = "Hello world!"
var mysubstring:String

// Example 1
mysubstring = mystring.substring(start: 1, length: 4)
// mysubstring is now "Hell"

// Example 2
mysubstring = mystring.substring(start: 7, length: 5)
// mysubstring is now "world"

// Example 3
mysubstring = mystring.substring(start: 7, length: 10)
// mysubstring is now "world!"

// Example 4
mysubstring = mystring.substring(start: 1, length: 0)
// mysubstring is now "" because length: 0 is invalid

Here is the String extension for substring:

extension String {
    func substring(start:Int, length:Int) -> String {
        let stringlength:Int = self.count
        var returnvalue:String = ""
        if start <= stringlength && length > 0 {
            let lowerbound = self.index(self.startIndex, offsetBy: start - 1)
            if start + length - 1 > stringlength { // Return through end of string.
                returnvalue = String(self[lowerbound...])
            } else { // Start and end.
                let upperbound = self.index(lowerbound, offsetBy: length - 1)
                returnvalue = String(self[lowerbound...upperbound])
            }
        }
        return returnvalue
    }
}