首页 > 代码库 > iOS: 在Swift中优雅的实现Substring

iOS: 在Swift中优雅的实现Substring

在Swift中,当我们想要截取某个字符串时,方法如下:

let carNumber = "沪A12345"let startIndex = advance(userCar.carPlateNumber.startIndex, 0)let endIndex = advance(startIndex, 1)let range = startIndex..<endIndexprintln(carNumber[range]) // 输出沪


呃,好怀念substring方法啊,那我们就自己实现一个吧。

extension String {    subscript (r: Range<Int>) -> String {        get {            let startIndex = advance(self.startIndex, r.startIndex)            let endIndex = advance(startIndex, r.endIndex - r.startIndex)                        return self[Range(start: startIndex, end: endIndex)]        }    }}


调用很简单,示例如下:

var s = "Hello, playground"println(s[0...5]) // ==> "Hello,"println(s[0..<5]) // ==> "Hello"


感谢Rob Napier http://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift

iOS: 在Swift中优雅的实现Substring