如何在Swift中使用substringToIndex?

时间:2014-07-23 07:52:15

标签: swift substring

我在这一行遇到编译器错误:

UIDevice.currentDevice().identifierForVendor.UUIDString.substringToIndex(8)

键入' String.Index'不符合协议' IntegerLiteralConvertible'

我的目的是获取子字符串,但是如何?

1 个答案:

答案 0 :(得分:181)

在Swift中,String索引尊重字形集群,而IndexType不是Int。您有两种选择 - 将字符串(您的UUID)强制转换为NSString,并将其用作“之前”,或者为第n个字符创建索引。

两者都如下所示:

但是,该方法在Swift版本之间发生了根本性的变化。阅读以下版本......

Swift 1

let s: String = "Stack Overflow"
let ss1: String = (s as NSString).substringToIndex(5) // "Stack"
//let ss2: String = s.substringToIndex(5)// 5 is not a String.Index
let index: String.Index = advance(s.startIndex, 5)
let ss2:String = s.substringToIndex(index) // "Stack"

CMD-点击substringToIndex会让您误解为NSString定义,但CMD点击String会发现以下内容:

extension String : Collection {
    struct Index : BidirectionalIndex, Reflectable {
        func successor() -> String.Index
        func predecessor() -> String.Index
        func getMirror() -> Mirror
    }
    var startIndex: String.Index { get }
    var endIndex: String.Index { get }
    subscript (i: String.Index) -> Character { get }
    func generate() -> IndexingGenerator<String>
}

斯威夫特2
正如评论员@DanielGalasko指出advance现在已经改变了......

let s: String = "Stack Overflow"
let ss1: String = (s as NSString).substringToIndex(5) // "Stack"
//let ss2: String = s.substringToIndex(5)// 5 is not a String.Index
let index: String.Index = s.startIndex.advancedBy(5) // Swift 2
let ss2:String = s.substringToIndex(index) // "Stack"

Swift 3
在Swift 3中,它再次发生了变化:

let s: String = "Stack Overflow"
let ss1: String = (s as NSString).substring(to: 5) // "Stack"
let index: String.Index = s.index(s.startIndex, offsetBy: 5)
var ss2: String = s.substring(to: index) // "Stack"

Swift 4
在Swift 4中,还有另一个变化:

let s: String = "Stack Overflow"
let ss1: String = (s as NSString).substring(to: 5) // "Stack"
let index: String.Index = s.index(s.startIndex, offsetBy: 5)
var ss3: Substring = s[..<index] // "Stack"
var ss4: String = String(s[..<index]) // "Stack"