无法在Swift 3中创建范围 [英] Can't create a range in Swift 3
问题描述
我正在尝试在Swift 3中建立一个范围,该范围已经在Swift 2中存在,但它一直给我这个错误:
String may not be indexed with 'Int', it has variable size elements
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<Index>?
expiredRange is a Range<Index>?
在Swift 2中,我有:
In Swift 2, I had:
let range = expireRange!.startIndex.advancedBy(7)...expireRange!.startIndex.advancedBy(16)
推荐答案
在Swift 3中,集合移动其索引",请参见 关于集合和指数的新模型
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屋!