如何在Swift中使用substringToIndex?

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

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

types“String.Index”不符合协议“IntegerLiteralConvertible”

我的意图是获取子string,但如何?

在Swift中, String索引尊重字形集群,并且IndexType不是Int 。 你有两个select – 把string(你的UUID)转换成一个NSString,并用它作为“before”,或者创build一个索引到第n个字符。

两者如下所示:

然而,这个方法在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> } 

Swift 2
正如评论员@DanielGalasko所指出的,现在已经改变了…

 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" 

斯威夫特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"