With the new ways of handling string in Swift 4, I'm trying to wrap my head around how to write the equivalent of the Mid function from other languages (visual basic, etc), so that
let testString = "0123456"
print Mid(testString, 2,4) // "1234" (or "2345" would work too)
This question is the same idea, but everything there predates Swift 4. If the answer there by jlert is still the best way to do things in Swift 4, that works, although it seems like so much has changed that the best practice to do this may have changed as well.
I would take a different approach using String.Index and return a Substring instead of a new String object. You can also add precondition to restrict improper use of that method:
func mid(_ string: String, _ positon: Int, length: Int) -> Substring {
precondition(positon < string.count, "invalid position")
precondition(positon + length <= string.count, "invalid substring length")
let lower = string.index(string.startIndex, offsetBy: positon)
let upper = string.index(lower, offsetBy: length)
return string[lower..<upper]
}
let testString = "0123456"
mid(testString, 2, length: 4) // "2345"
Another option would be creating that method as a string extension:
extension String {
func mid(_ positon: Int, length: Int) -> Substring {
precondition(positon < count, "invalid position")
precondition(positon + length <= count, "invalid substring length")
let lower = index(startIndex, offsetBy: positon)
let upper = index(lower, offsetBy: length)
return self[lower..<upper]
}
}
let testString = "0123456"
testString.mid(2, length: 4) // "2345"