我有以下简单的代码写在Swift 3:

let str = "Hello, playground"
let index = str.index(of: ",")!
let newStr = str.substring(to: index)

在Xcode 9 beta 5中,我得到了以下警告:

'substring(to:)'已弃用:请使用带有'partial range from'操作符的字符串切片下标。

这个部分范围的切片下标如何在Swift 4中使用?


当前回答

一些有用的扩展:

extension String {
    func substring(from: Int, to: Int) -> String {
        let start = index(startIndex, offsetBy: from)
        let end = index(start, offsetBy: to - from)
        return String(self[start ..< end])
    }

    func substring(range: NSRange) -> String {
        return substring(from: range.lowerBound, to: range.upperBound)
    }
}

其他回答

用这个方法你可以得到字符串的特定范围。你需要传递起始索引和你想要的字符总数。

extension String{
    func substring(fromIndex : Int,count : Int) -> String{
        let startIndex = self.index(self.startIndex, offsetBy: fromIndex)
        let endIndex = self.index(self.startIndex, offsetBy: fromIndex + count)
        let range = startIndex..<endIndex
        return String(self[range])
    }
}

转换子字符串(Swift 3)到字符串切片(Swift 4)

在Swift 3,4中:

let newStr = str.substring(to: index) // Swift 3
let newStr = String(str[..<index]) // Swift 4

let newStr = str.substring(from: index) // Swift 3
let newStr = String(str[index...]) // Swift 4 

let range = firstIndex..<secondIndex // If you have a range
let newStr = = str.substring(with: range) // Swift 3
let newStr = String(str[range])  // Swift 4

Swift 4/5更短:

let string = "123456"
let firstThree = String(string.prefix(3)) //"123"
let lastThree = String(string.suffix(3)) //"456"

希望这将帮助更多:-

var string = "123456789"

如果你想在某个特定的索引后面加一个子字符串。

var indexStart  =  string.index(after: string.startIndex )// you can use any index in place of startIndex
var strIndexStart   = String (string[indexStart...])//23456789

如果你想在末尾删除某个字符串后获得子字符串。

var indexEnd  =  string.index(before: string.endIndex)
var strIndexEnd   = String (string[..<indexEnd])//12345678

还可以使用以下代码创建索引:—

var  indexWithOffset =  string.index(string.startIndex, offsetBy: 4)

你的代码转换到Swift 4也可以这样做:

let str = "Hello, playground"
let index = str.index(of: ",")!
let substr = str.prefix(upTo: index)

你可以使用下面的代码来创建一个新的字符串:

let newString = String(str.prefix(upTo: index))