0

This is the JS code:

 const textLength = textContent.length;
    let string = '';
        for (let i = 0; i < textLength; i++) {
          if (string !== '' && offsetsSet.has(i)) {
            parts.push(string);
            string = '';
          }
          string += textContent[i];
        }

This is my swift code which I have ported to swift:

     override func getTextPart() -> String {
        guard let textNode = getLatest() as? TextNode else {
          return text
        }
        return textNode.text
      }
 public func splitText(splitOffsets: [Int]) throws -> [Node] {
      let textContent = getTextPart()
      let textLength = textContent.count
      let offsetsSet = Set(splitOffsets)
      var parts = [String]()
      var string = ""
    
          for i in 0..<textLength {
            if string != "" && offsetsSet.contains(i) {
              parts.append(string)
              string = ""
            }
              string += textContent[i] //Error: No exact matches in call to subscript 
          }
}

I'm getting error in this line: string += textContent[i]//Error: No exact matches in call to subscript. How do I write this in swift?

  • Swift String is not be indexed by integers. You would need to extend String if you would like to do so. https://stackoverflow.com/a/38215613/2303865 – Leo Dabus Feb 16 '22 at 20:18
  • or try `for i in textContent.indices {` and append the character `string.append(textContent[i])` – Leo Dabus Feb 16 '22 at 20:19
  • @LeoDabus I think `textContent.enumerated()` would be more convenient in this case. – Sweeper Feb 16 '22 at 20:20
  • @Sweeper there is many alternatives. I would go for the string indices. Sure OP would need to change some other checks like `offsetsSet.contains(i)` which is unclear where is coming from. – Leo Dabus Feb 16 '22 at 20:21
  • 1
    @LeoDabusThanks it helped. – newUserA A Feb 16 '22 at 20:48
  • Rather than replacing JS to Swift word-for-word, you should spend some effort to learn more about the various Swift conventions/idoms/styles. For example, one thing to notice is that JS has a really bare-bones standard library, so a lot of stuff like this gets hand-rolled unless you already are using third party libraries like Lodash to provide these essentials. I would suggest you post this snippet to codereview.stackexchange.ca, because there's a lot that can be simplified – Alexander Feb 17 '22 at 03:07

0 Answers0