Can't create a range in Swift 3

点点圈 提交于 2019-12-18 02:19:10

问题


I am trying to make a range in Swift 3 that I already had in Swift 2 but it keeps giving me this error: String may not be indexed with 'Int', it has variable size elements

Here is my code:

let range = expireRange!.startIndex.advancedBy(n: 7) ..< expireRange!.startIndex.advancedBy(n: 16)

expiredRange is a Range<Index>?

In Swift 2, I had:

let range = expireRange!.startIndex.advancedBy(7)...expireRange!.startIndex.advancedBy(16)

回答1:


In Swift 3, "Collections move their index", see A New Model for Collections and Indices on Swift evolution.

Here is an example for String ranges and indices:

let string = "ABCDEFG"
if let range = string.range(of: "CDEF") {
    let lo = string.index(range.lowerBound, offsetBy: 1)
    let hi = string.index(range.lowerBound, offsetBy: 3)
    let subRange = lo ..< hi
    print(string[subRange]) // "DE"
}

The

public func index(_ i: Index, offsetBy n: IndexDistance) -> Index

method is called on the string to calculate the new indices from the range (which has properties lower/upperBound now instead of start/endIndex).



来源:https://stackoverflow.com/questions/38070273/cant-create-a-range-in-swift-3

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