shakked shakked - 5 months ago 18
Swift Question

How to extract phrase from string using Range?

This sounds easy, but I am stumped. The syntax and functions of Range are very confusing to me.

I have a URL like this:

https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post


I need to extract the part
#global-best-time-to-post
, essentially the
#
to the end of the string.

urlString.rangeOfString("#")
returns
Range

Then I tried doing this assuming that calling
advanceBy(100)
would just go to the end of the string but instead it crashes.

hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100))

Answer

Easiest and best way to do this is use NSURL, I included how to do it with split and rangeOfString:

import Foundation

let urlString = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"

// using NSURL - best option since it validates the URL
if let url = NSURL(string: urlString),
  fragment = url.fragment {
  print(fragment)
}
// output: "global-best-time-to-post"

// using split - pure Swift, no Foundation necessary
let split = urlString.characters.split("#")
if split.count > 1,
  let fragment = split.last {
  print(String(fragment))
}
// output: "global-best-time-to-post"

// using rangeofString - asked in the question
if let endOctothorpe = urlString.rangeOfString("#")?.endIndex {
  // Note that I use the index of the end of the found Range 
  // and the index of the end of the urlString to form the 
  // Range of my string
  let fragment = urlString[endOctothorpe..<urlString.endIndex]
  print(fragment)
}
// output: "global-best-time-to-post"