0

I have a pretty basic code, that makes 2 String.Index ranges from an existing websiteContent String like so:

let test1 = websiteContent.range(of: startString, options: NSString.CompareOptions.literal, range: websiteContent.startIndex..<websiteContent.endIndex)

let test2 = websiteContent.range(of: endString, options: NSString.CompareOptions.literal, range: websiteContent.startIndex..<websiteContent.endIndex)

Then it prints the text between the 2 ranges:

if let beginning = test1, let end = test2 {
    print(websiteContent[beginning.lowerBound..<end.upperBound])
}

This works just fine, my problem is that when I try to store this String value I just printed it throws an error message. The way I tried to store it is this:

if let beginning = test1, let end = test2 {
    let why : String = websiteContent[beginning.lowerBound..<end.upperBound]
}

And the error message says: Subscript 'subscript(_:)' requires the types 'String.Index' and 'Int' be equivalent

Could you please help me understand what do I do wrong?

harcipulyka
  • 117
  • 1
  • 6

1 Answers1

1

This is actually a bug, the error is misleading.

You have to create a String from the Substring, annotating the type is not sufficient.

if let beginning = test1, let end = test2 {
    let why = String(websiteContent[beginning.lowerBound..<end.upperBound])
}

Side note:

You can omit , range: websiteContent.startIndex..<websiteContent.endIndex, the range of the whole string is the default.

vadian
  • 274,689
  • 30
  • 353
  • 361