Drux Drux - 3 months ago 15
Swift Question

Creating Range<String.Index> from constant Ints

What is wrong with this piece of code for constructing a range that should then serve in a call to

substringWithRange
?

let range = Range<String.Index>(start: 0, end: 3)


The Swift compiler (in Xcode 7.1.1) marks it with this error message:


Cannot invoke initializer for type 'Range<Index>' with an argument list of type '(start: Int, end: Int)'

Tim Tim
Answer

You need to reference the startIndex of a specific string, then advance:

let longString = "Supercalifragilistic"
let startIndex = longString.startIndex
let range = Range(start: startIndex, end: startIndex.advancedBy(3))
Comments