shakked shakked - 4 months ago 6x
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:

I need to extract the part
, essentially the
to the end of the string.


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

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


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

import Foundation

let urlString = ""

// using NSURL - best option since it validates the URL
if let url = NSURL(string: urlString),
  fragment = url.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 {
// 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]
// output: "global-best-time-to-post"