Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

Cannot invoke initializer for type 'Range<_>' with an argument list of type '(Range<String.Index>)' in func substring(start:end:) #85

Closed
boywithaxe opened this issue Jun 5, 2018 · 7 comments

Comments

@boywithaxe
Copy link


func substring(_ start: Int, end: Int) -> String {
return String(self[Range(self.index(self.startIndex, offsetBy: start) ..< self.index(self.startIndex, offsetBy: end))])

    }

the above function contains a method resulting in the following error:

Cannot invoke initializer for type 'Range<_>' with an argument list of type '(Range<String.Index>)' in Xcode 10 beta 1.

I appreciate this is a very early report, but does seem to be a swift version issue.

@LeonardoCardoso
Copy link
Owner

Most probably it is. I'll have a look ASAP.

@LeonardoCardoso
Copy link
Owner

Changes in master.

@MichaelLuoSyd
Copy link

Hi, may I know how to solve this issue please? I am having the same problem. Thanks

@jpmhglance
Copy link

Was this it?

-         return String(self[Range(self.index(self.startIndex, offsetBy: start) ..< self.index(self.startIndex, offsetBy: end))])
+         return self.substring(NSRange(location: start, length: end - start))

I fixed a similar error in my code this way instead:

-                        self.text = String(str[Range(startIndex ..< nextToEndIndex)])
+                        self.text = String(str[startIndex ..< nextToEndIndex])

@asharmaVelsof
Copy link

asharmaVelsof commented Oct 16, 2018

I fixed the error by replacing the code with

let range = self.index(self.startIndex, offsetBy: r.lowerBound)..<self.index(self.startIndex, offsetBy: r.upperBound) return String(self[range])

@boywithaxe
Copy link
Author

boywithaxe commented Oct 26, 2018

That's the line that fixes it. the issue recurred in the latest version, but making the following change fixes it in Swift 4 and up

`

  •     return String(self[Range(self.index(self.startIndex, offsetBy: start) ..< self.index(self.startIndex, offsetBy: end))])
    
  •     return self.substring(NSRange(location: start, length: end - start))`
    

@jpmhglance
Copy link

@boywithaxe beware though, substring(with: NSRange) is an NSString method which indexes strings differently that Swift strings. Your fix will definitely have different behaviour if the string contains certain emoji character, look into Unicode Extended Grapheme Clusters.

Did you try just taking out Range( .. )? A la:

return String(self[self.index(self.startIndex, offsetBy: start) ..< self.index(self.startIndex, offsetBy: end)])

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants