Reputation: 1185
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.
Upvotes: 9
Views: 24110
Reputation: 119242
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)
Upvotes: 10
Reputation: 28799
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
Upvotes: 3