0

I have a string "John+20", I would like to extract out "John", so, I tried following based on this answer:

// data contains value "John+20"
static func getName(fromString data: String?) {
  guard let myData = data else {
      return
  }

  let idx = myData.index(of: "+")
  //Compiler ERROR: Generic parameter 'Self' could not be inferred
  let name = String(myData[..<idx])
}

But I get the error I mentioned in code comment, why is that?

I am using Swift 4.1 in my iOS project.

CZ54
  • 5,488
  • 1
  • 24
  • 39
Leem
  • 17,220
  • 36
  • 109
  • 159

1 Answers1

0

I guess the index is an optional as well. Try :

// data contains value "John+20"
static func getName(fromString data: String?) {
  guard let myData = data else, let idx = myData.index(of: "+") {
      return
  }

  let name = String(myData[..<idx])
}
CZ54
  • 5,488
  • 1
  • 24
  • 39