1

I am new to swift, I want to get substring from specified range. But I am getting some errors.

I have found similar questions on getting subString from range, but those couldn't work for me. I am using XCode 10.1 and swift 4.2. I have getting error while getting substring from specified range. I have tried like this (Sample Code)

let textStr = "Sample text here"

let newRange = NSMakeRange(4,9)

let startIndex = textStr?.index((textStr?.startIndex)!, offsetBy: newRange.location)
let endIndex = textStr?.index((textStr?.startIndex)!, offsetBy: newRange.length)

let newHashtagRange = startIndex..<endIndex

let newHashTagFound = textStr[newHashtagRange]

Error:

I am getting below error for this line of code

let newHashtagRange = startIndex..<endIndex

Binary operator '..<' cannot be applied to two 'String.Index?' operands


I just struct here from last two days.

But in Objective-C just need one line of code like SubStringFromRange(range).

1 Answers1

1

You are getting an error because both startIndex and endIndex are optionals due to the optional chain you have when defining them.

That is odd because, in your example code, textStr is not actually optional and the optional chain wouldn't even compile. My guess is you were attempting to shorten the example. I will assume textStr is meant to be optional and show you how to avoid using forced unwrapping which is almost always a bad idea. Also, you are getting the end index incorrectly. You need to do an offset from the calculated start index with the length. That leaves you with this:

let textStr: String? = "Sample text here"

if let textStr = textStr {
    let newRange = NSMakeRange(4,9)

    let startIndex = textStr.index(textStr.startIndex, offsetBy: newRange.location)
    let endIndex = textStr.index(startIndex, offsetBy: newRange.length)

    let newHashtagRange = startIndex..<endIndex

    let newHashTagFound = textStr[newHashtagRange]
}

However, a Range can be initialized from an NSRange which is reliable and built in (it returns an optional in case the range is out of bounds):

let textStr: String? = "Sample text here"

let newRange = NSMakeRange(4,9)
if let textStr = textStr
    , let newHashtagRange = Range(newRange, in: textStr)
{
    let newHashTagFound = textStr[newHashtagRange]
}
drewag
  • 93,393
  • 28
  • 139
  • 128