如何在Swift中使用substringToIndex?

前端之家收集整理的这篇文章主要介绍了如何在Swift中使用substringToIndex?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Type ‘String.Index’ does not conform protocol ‘IntegerLiteralConvertible’3答案我在这行得到编译器错误
UIDevice.currentDevice().identifierForVendor.UUIDString.substringToIndex(8)

类型“String.Index”不符合协议“IntegerLiteralConvertible”

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

在Swift中,字符串索引涉及字形集群,而IndexType不是Int。您有两个选择 – 将字符串(您的UUID)转换为NSString,并将其用作“before”,或者为第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点击字符串,你会发现以下:

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"
原文链接:https://www.f2er.com/swift/321471.html

猜你在找的Swift相关文章