Creating Range<String.Index> from constant Ints

ぃ、小莉子 提交于 2020-01-06 02:27:24

问题


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


回答1:


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



回答2:


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)



来源:https://stackoverflow.com/questions/33815495/creating-rangestring-index-from-constant-ints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!