Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4.2, String firstIndex() function error in Xcode playground

Tags:

xcode

swift

I was reading "The Swift Programming Language Swift 4.2" and in "Strings and Characters" chapter under "Substrings" section, the following code is given as an example:

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)

I copied and pasted this chunk into my Xcode playground; however, I got the following error:

Playground execution failed:

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

I checked that there is indeed a method called firstIndex() for the String class on https://developer.apple.com/documentation/swift/string.

I have import UIKit; at the top of my playground.

Can you let me know why I might be getting this error?

like image 510
Anil Celik Maral Avatar asked Jul 30 '18 14:07

Anil Celik Maral


1 Answers

You can try index(of

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

as firstIndex exists in Xcode 10 beta Doc

like image 126
Sh_Khan Avatar answered Nov 02 '22 20:11

Sh_Khan