There are two problems:
fieldName.endIndex is the "one past the end" position of the string,
it has no successor.
- You must not use the index of one string as the subscript for
a different string. That may work in some cases, but can
crash with a runtime exception if the strings contain
characters outside of the "basic multilingual plane" (Emojis, flags, ...).
A working variant would be (Swift 2.2):
let fieldName = "VERSION:"
let versionField = "VERSION:4.1"
if versionField.hasPrefix(fieldName) {
let version = versionField.substringFromIndex(
versionField.startIndex.advancedBy(fieldName.characters.count))
print(version) // 4.1
} else {
print("No version found")
}
or alternatively:
if let range = versionField.rangeOfString(fieldName)
where range.startIndex == versionField.startIndex {
let version = versionField.substringFromIndex(range.endIndex)
print(version) // 4.1
} else {
print("No version found")
}
You can remove the constraint
where range.startIndex == versionField.startIndex
if the field should be found anywhere in the string.
Swift 3:
if versionField.hasPrefix(fieldName) {
let version = versionField.substring(
from: versionField.index(versionField.startIndex, offsetBy: fieldName.characters.count))
print(version) // 4.1
} else {
print("No version found")
}
or alternatively,
if let range = versionField.range(of: fieldName),
range.lowerBound == versionField.startIndex {
let version = versionField.substring(from: range.upperBound)
print(version) // 4.1
} else {
print("No version found")
}