如何在 Swift 中使用 substringToIndex? [英] How to use substringToIndex in Swift?

查看:34
本文介绍了如何在 Swift 中使用 substringToIndex?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get compiler error at this line:

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

类型String.Index"不符合协议IntegerLiteralConvertible"

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

My intention is to get the substring, but how?

推荐答案

在 Swift 中,String 索引遵循字素簇,并且 IndexType 不是 Int.您有两种选择 - 将字符串(您的 UUID)转换为 NSString,并将其用作before",或者创建第 n 个字符的索引.

In Swift, String indexing respects grapheme clusters, and an IndexType is not an Int. You have two choices - cast the string (your UUID) to an NSString, and use it as "before", or create an index to the nth character.

两者都如下图所示:

然而,该方法在 Swift 版本之间发生了根本性的变化.向下阅读以获取更高版本...

However, the method has changed radically between versions of Swift. Read down for later versions...

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 会发现以下内容:

CMD-Click on substringToIndex confusingly takes you to the NSString definition, however CMD-Click on String and you will find the following:

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 现在已经改变了......

Swift 2
As commentator @DanielGalasko points out advance has now changed...

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"

斯威夫特 3
在 Swift 3 中,它又发生了变化:

Swift 3
In Swift 3, it's changed again:

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 中,还有另一个变化:

Swift 4
In Swift 4, yet another change:

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"

这篇关于如何在 Swift 中使用 substringToIndex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆