Reputation: 12670
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)'
Upvotes: 3
Views: 4166
Reputation: 3006
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)
Upvotes: 1
Reputation: 2098
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))
Upvotes: 8