0

Consider dir that is a Range<String :

let dir = url.absoluteString.range(of: "/", options: .backwards)

When trying to convert dir to a String via String(dir) we have:

Initializer 'init(_:)' requires that 'Range<String.Index>?' conform to 'LosslessStringConvertible'   

I have looked at a number of questions regarding swift substrings and ranges and have not found an exact answer to this. So how can the Range be converted to a String?

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • Can you show some sample inputs and outputs? Converting a `Range` to a `String` doesn't make sense to me... – Sweeper Jun 30 '20 at 02:43
  • Related: https://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift – vadian Jun 30 '20 at 04:28

1 Answers1

1
if let range = url.range(of: "/", options: .backwards) {
   let substr = url[range]
}
nghiahoang
  • 538
  • 4
  • 10
  • 1
    What is the purpose of this? The substring will always be equal to the search. – Leo Dabus Jun 30 '20 at 02:51
  • If you want to fetch the name of a file or a directory you don't need to reinvent the wheel. `url.lastPathComponent` – Leo Dabus Jun 30 '20 at 02:52
  • 1
    If you want the substring from the beginning to before /. It should be let substr = url[url.startIndex.. – nghiahoang Jun 30 '20 at 02:54
  • @nghiahoang this is also pointless. `url.deletingLastPathComponent()`. If OP needs a string with the url scheme `url.deletingLastPathComponent().absoluteString` or without the scheme `url.deletingLastPathComponent().path` – Leo Dabus Jun 30 '20 at 02:55
  • this is not helping me. i would take back the upvote if possible – WestCoastProjects Jun 30 '20 at 03:36
  • so if your url is `https://google.com` . What is value you want from String(dir)? – nghiahoang Jun 30 '20 at 03:37
  • @LeoDabus I'm tired of memorizing these strange library method names. I can't easily get autocompletion on them either. Just a simple understanding of how to do substrings and reverse find index etc. PITA in swift it seems. I've tried using the `s[start.. – WestCoastProjects Jun 30 '20 at 03:38
  • you can use PartialRangeUpTo `string[.. – Leo Dabus Jun 30 '20 at 03:41
  • There is also the URLResourceValues you can use when dealing with fileURLs `if let name = (try? url.resourceValues(forKeys: [.nameKey]))?.name {` – Leo Dabus Jun 30 '20 at 03:46
  • I do agree about autocompletion is kind of sensitive. Try cleaning your project or testing it in a new playground file. – Leo Dabus Jun 30 '20 at 03:55
  • I'm going to need some third party libraries to retain some fraction of my head. Looking at `swifterswift` . let's see. Yea it has subscript and slicing and slew of other conveniences. So swift will be a language i don't use w/o additional tools. That's not the end of the world – WestCoastProjects Jun 30 '20 at 04:41