WestCoastProjects
WestCoastProjects

Reputation: 63062

How to convert a Range<String> to a String in Swift

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?

Upvotes: 0

Views: 69

Answers (1)

nghiahoang
nghiahoang

Reputation: 568

if let range = url.range(of: "/", options: .backwards) {
   let substr = url[range]
}

Upvotes: 1

Related Questions