Swift 4.2,Xcode Playground中的String firstIndex()函数错误

时间:2018-07-30 14:34:50

标签: swift xcode

我正在阅读“ The Swift Programming Language Swift 4.2”和“子字符串”部分下“字符串和字符”一章中,给出以下代码作为示例:

let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"

// Convert the result to a String for long-term storage.
let newString = String(beginning)

我复制了此块并将其粘贴到我的Xcode游乐场中;但是,出现以下错误:

Playground execution failed:

error: MyPlayground.playground:6:13: error: value of type 'String' has 
no member 'firstIndex'
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
            ^~~~~~~~ ~~~~~~~~~~

我检查了https://developer.apple.com/documentation/swift/string上的String类是否确实有一个名为firstIndex()的方法。

我在操场的顶部有 import UIKit;

您能告诉我为什么会出现此错误吗?

1 个答案:

答案 0 :(得分:4)

您可以尝试index(of

let index = greeting.index(of: ",") ?? greeting.endIndex

在Xcode 10 beta Doc中存在firstIndex