我有以下简单的代码写在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中使用?


当前回答

我写了一个字符串扩展替换' string: subString:'

extension String {
    
    func sliceByCharacter(from: Character, to: Character) -> String? {
        let fromIndex = self.index(self.index(of: from)!, offsetBy: 1)
        let toIndex = self.index(self.index(of: to)!, offsetBy: -1)
        return String(self[fromIndex...toIndex])
    }
    
    func sliceByString(from:String, to:String) -> String? {
        //From - startIndex
        var range = self.range(of: from)
        let subString = String(self[range!.upperBound...])
        
        //To - endIndex
        range = subString.range(of: to)
        return String(subString[..<range!.lowerBound])
    }
    
}

用法:“日期(1511508780012+0530)”sliceByString(from: "(", to: "+") 示例结果:"1511508780012"

PS:可选选项被强制展开。如有需要,请添加类型安全检查。

其他回答

var str = "Hello, playground"
let indexcut = str.firstIndex(of: ",")
print(String(str[..<indexcut!]))
print(String(str[indexcut!...]))

你可以试着用这种方法,并会得到适当的结果。

如果你只是想获取一个特定字符的子字符串,你不需要先找到索引,你可以只使用prefix(while:)方法

let str = "Hello, playground"
let subString = str.prefix { $0 != "," } // "Hello" as a String.SubSequence

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

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 4也可以这样做:

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

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

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

我使用的简单方法是:

String(Array(str)[2...4])