Dmitry L.
Dmitry L.

Reputation: 138

String.endIndex incrementing error

I have a case like that:

var fieldName = "VERSION"
var versionField = "VERSION:4.1"

var version = versionField.substringFromIndex(fieldName.endIndex.successor())

The last line generate a runtime error "fatal error: cannot increment endIndex". It's happen because swift doesn't know what the next index after biggest one. Looks like this solution works for swift 1.* only. But is there any way to solve this issue succinctly for new swift version?
Thanks for answers.

Upvotes: 0

Views: 733

Answers (1)

Martin R
Martin R

Reputation: 539745

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")
}

Upvotes: 4

Related Questions