LeonardoCardoso / SwiftLinkPreview

It makes a preview from an URL, grabbing all the information such as title, relevant texts and images.
https://leocardz.com/swift-link-preview-5a9860c7756f
MIT License
1.37k stars 196 forks source link

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

Closed boywithaxe closed 3 years ago

boywithaxe commented 6 years ago

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)' in Xcode 10 beta 1.

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

LeonardoCardoso commented 6 years ago

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

LeonardoCardoso commented 6 years ago

Changes in master.

MichaelLuoSyd commented 6 years ago

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

jpmhglance commented 6 years ago

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 commented 5 years ago

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 commented 5 years ago

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

`

jpmhglance commented 5 years ago

@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)])