Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type 'Range<Int>' to expected argument type 'Range<Index>' (aka 'Range<String.CharacterView.Index>')

I have a string here, which I am trying to substring.

let desc = "Hello world. Hello World."
var stringRange = 1..<5
desc.substringWithRange(stringRange)

However Swift gives me an error with this. What have I done wrong? I am using the new notation of the stringRange because it doesn't let me use the old one.

like image 474
Big Green Alligator Avatar asked Apr 20 '16 09:04

Big Green Alligator


2 Answers

The Range you have created does not have the correct type, it is inferred to be an Int. You need to create the range from the string itself:

let desc = "Hello world. Hello World."
let stringRange = desc.startIndex..<desc.startIndex.advancedBy(5)
let sub = desc[stringRange]

It's slightly more complex with String. Alternatively, go back to NSString and NSRange:

let range = NSMakeRange(0, 5)
let sub2 = (desc as NSString).substringWithRange(range)
like image 113
jrturton Avatar answered Oct 16 '22 17:10

jrturton


Your 1..<5 is from type Range<Int>, while the method substringWithRange expects a value from type Range<Index>

let desc = "Hello world. Hello World."

var dd = desc.substringWithRange(desc.startIndex..<desc.startIndex.advancedBy(5))

You may apply advanceBy to the desc.startIndex as well

like image 44
William Kinaan Avatar answered Oct 16 '22 18:10

William Kinaan