'init(start:end:)' 已弃用:它将在 Swift 中删除 3. 使用 '..<' 运算符

'init(start:end:)' is deprecated: it will be removed in Swift 3. Use the '..<' operator

我正在使用以下代码:

var continousDigitsRange:Range<Int> = Range<Int>(start: 0, end: 0)

自从更新到 Xcode 7.3 (Swift 2.2) 我得到以下提示:

'init(start:end:)' is deprecated: it will be removed in Swift 3. Use the '..<' operator.

我不清楚如何 "translate" 使用“使用 '..<' 运算符来正确

你应该简单地写

var continousDigitsRange1:Range<Int> = 0..<0

或者如果你想更简单

var continousDigitsRange = 0..<0

The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.

The half-open range operator (a..<b) defines a range that runs from a to b, but does not include b. It is said to be half-open because it contains its first value, but not its final value. As with the closed range operator, the value of a must not be greater than b. If the value of a is equal to b, then the resulting range will be empty.

The Swift Programming Language (Swift 2.2) - Basic Operators

var continousDigitsRange:Range<Int> = Range<Int>(start: 0, end: 0)
--to--
var continousDigitsRange:Range<Int> = 0..<0

另外值得注意的是,要substringWithRange一个String,你现在可以使用

let theString = "Hello, how are you"
let range = theString.startIndex.advancedBy(start) ..< theString.startIndex.advancedBy(end)
theString.substringWithRange(range)

显示 bmichotte 的完整答案...

let theString = "Hello, how are you today my friend"
    let start = 3
    let end = 15
    let range = theString.startIndex.advancedBy(start) ..< theString.startIndex.advancedBy(end)
    let p = theString.substringWithRange(range)
    print("this is the middle bit>\(p)<")

这是中间位>瞧瞧,<

参考swift3.0

补充几点

//可数范围示例。

let range1 = 0..<5

可数封闭范围示例

let range2 = 0...5

//范围从边界

let range = Range(uncheckedBounds: (range1.lowerBound,range1.upperBound))

//获取substringRange的距离。

let str = "Hello, how are you"
let substringRange = str.characters.indices

//低于Swift 3.0

let length = substringRange.distance(from: substringRange.startIndex, to: substringRange.endIndex)

//对于Swift 3.0

let length2 = str.distance(from: substringRange.startIndex, to: substringRange.endIndex)

我一直有一个函数可以获取字符串的子字符串范围。这是我为 Swift 3:

更新的函数
func getSubStringRange(fullString: String, fromIndex: Int, subStringSize: Int) -> Range<String.Index> {
    let startIndex = fullString.characters.index(fullString.startIndex, offsetBy: fromIndex)
    let endIndex = fullString.characters.index(startIndex, offsetBy: subStringSize)

    let subStringRange = startIndex..<endIndex

    return subStringRange
}

该函数非常容易解释 - 您传入一个字符串 (fullString)、子字符串开始处的字符串索引 (fromIndex) 以及子字符串的大小 (subStringSize)。

示例:

let greeting = "Hi, my name is Nathaniel"
let getName = greeting[getSubStringRange(fullString: greeting, fromIndex: 15, subStringSize: 9)]

print("Name: \(getName)")

-> 打印:"Name: Nathaniel"