In general it’s better to avoid walking through a string character by character. Rather, you should try to implement your string processing in terms of higher-level constructs. For example, you wrote:
I want to remove the first 21 characters so that I am jsut left with "Test1" as my label's stringValue?
which you can do in a variety of different ways:
if the prefix can vary but the separator is fixed, you can search for the separator
if the prefix is fixed, you can search for the prefix, but anchor that search at the start
if you know the suffix can’t contain a specific character, you can search backwards from that
you can split the string based on the separator and then extract parts
Pasted in below is code to do each of these.
There’s a bunch of advantages to moving to a higher-level abstraction, including:
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
import Foundation
let str = "Pixel Film Studios - Test1"
if let r = str.range(of: " - ") {
print(str.substring(from: r.upperBound))
} else {
print("separator not found")
}
// prints 'Test1'
if let r = str.range(of: "Pixel Film Studios - ", options: [.anchored]) {
print(str.substring(from: r.upperBound))
} else {
print("separator not found")
}
// prints 'Test1'
if let r = str.range(of: " ", options: [.backwards]) {
print(str.substring(from: r.upperBound))
} else {
print("separator not found")
}
// prints 'Test1'
let parts = str.components(separatedBy: " - ")
print(parts)
// prints '["Pixel Film Studios", "Test1"]'