0

I got an error message when I call the following method

pathString.removeSubrange(Range(pathString.startIndex..<pathString.index(pathString.startIndex, offsetBy: 7)))

Here is the error message

Cannot invoke initializer for type 'Range<_>' with an argument list of type '(Range)'

How would I change these statements to get rid of this error the transfer over to XCode 10 and Swift 4.2 is really giving me a hard time.

Looks like this

if pathString.contains("file://") {
    let startIndex = pathString.startIndex
    let endIndex = pathString.index(pathString.startIndex, offsetBy: 7)
    let range = startIndex..<endIndex
    pathString.removeSubrange(range)
}
Yury Imashev
  • 2,068
  • 1
  • 18
  • 32
HiDungLing
  • 237
  • 4
  • 14
  • thanks for the edit but does anyone have any idea – HiDungLing Sep 20 '18 at 21:43
  • Please don't hack your file url path. Learn the differences from absoluteString and path properties of a URL – Leo Dabus Sep 20 '18 at 22:02
  • @LeoDabus can you post an example of how i should use it – HiDungLing Sep 20 '18 at 22:04
  • Show your actual problem. You shouldn't be working with strings (path) anymore. You should use only URL. if you have no alternative just check if the file:// prefix is present use `URL(string:)` initializer if the scheme it is not present use `URL(fileURLWithPath:)` initializer. – Leo Dabus Sep 20 '18 at 22:13
  • This might help also https://stackoverflow.com/a/40643037/2303865 and https://stackoverflow.com/a/34135437/2303865 – Leo Dabus Sep 20 '18 at 22:15

2 Answers2

0

You don't need to call the Range initializer. Just do the following

pathString.removeSubrange(pathString.startIndex..<pathString.index(pathString.startIndex, offsetBy: 7))

or this, for more readability

let startIndex = pathString.startIndex
let endIndex = pathString.index(pathString.startIndex, offsetBy: 7)
let range = startIndex..<endIndex
pathString.removeSubrange(range)

UPDATE

In comments, Leo Dabus suggested the better solution

extension StringProtocol where Self: RangeReplaceableCollection {
    mutating func removePrefix(_ prefix: String) {
        if hasPrefix(prefix) {
            removeFirst(prefix.count)
        }
    }
}

After adding that you can simply call

pathString.removePrefix("file://")
Yury Imashev
  • 2,068
  • 1
  • 18
  • 32
0

Hi there this looks like it's solved by this answer: https://stackoverflow.com/a/50719696/7932935

In your case replace:

pathString.removeSubrange(Range(pathString.startIndex..<pathString.index(pathString.startIndex, offsetBy: 7)))

with:

pathString.removeSubrange(pathString.startIndex..<pathString.index(pathString.startIndex, offsetBy: 7))
Carlos S
  • 26
  • 5
  • I tested it on a Playground and it works for swift 4.2, like Yuri below is pathString a string? cheers! – Carlos S Sep 20 '18 at 22:18