0

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.

0

1 Answer 1

4

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")
}
Sign up to request clarification or add additional context in comments.

2 Comments

Note that OP has "fieldName = "VERSION" not fieldName = "VERSION:" so I guess it should be let version = versionField.substringFromIndex(range.endIndex.advancedBy(1)) right?
@EricAya: I changed that on purpose to simplify the code. range.endIndex.advancedBy(1) could be past the end of versionField, so you would have to check that first. Also it would not verify that the version field is followed by a colon.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.