Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)'

like image 805
Drux Avatar asked May 11 '26 17:05

Drux


2 Answers

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))
like image 56
Tim Avatar answered May 14 '26 07:05

Tim


You can use various ways

let startIndex = text.startIndex
let endIndex = text.endIndex

var range1 = startIndex.advancedBy(1) ..< text.endIndex.advancedBy(-4)
var range2 = startIndex.advancedBy(0) ..< startIndex.advancedBy(5)
var range3 = startIndex ..< endIndex

let substring = text.substringWithRange(range)

like image 38
Svitlana Avatar answered May 14 '26 07:05

Svitlana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!