无法在 Swift 3 中创建范围 [英] Can't create a range in Swift 3
问题描述
我试图在 Swift 3 中创建一个我在 Swift 2 中已经拥有的范围,但它一直给我这个错误:字符串不能用'Int'索引,它有可变大小的元素
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
这是我的代码:
let range = expireRange!.startIndex.advancedBy(n: 7) ..< expireRange!.startIndex.advancedBy(n: 16)
expiredRange 是 Range
expiredRange is a Range<Index>?
在 Swift 2 中,我有:
In Swift 2, I had:
let range = expireRange!.startIndex.advancedBy(7)...expireRange!.startIndex.advancedBy(16)
推荐答案
在 Swift 3 中,Collections move their index",参见集合和索引的新模型关于 Swift 进化.
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"
}
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index
方法在字符串上被调用来计算新的索引范围(现在具有属性 lower/upperBound
而不是start/endIndex
).
method is called on the string to calculate the new indices from the
range (which has properties lower/upperBound
now instead of
start/endIndex
).
这篇关于无法在 Swift 3 中创建范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!