Piercy
Piercy

Reputation: 493

Fill an array with strings from a txt file [Solution from XCode6 Beta1 no longer works]

A few weeks ago, I asked how to Fill an array with strings from a txt file.

A few answers (that worked) had been given, but since I updated Xcode 6 to Beta 3, they don't work anymore.

The code is this one:

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSString(contentsOfFile: path).componentsSeparatedByString("\n")

Since Beta 3, the following error is being displayed about NSString:

'init(contentsOfFile:)' is unavailable: APIs deprecated of iOS7 and earlier are unavailable in Swift

Upvotes: 1

Views: 328

Answers (1)

al45tair
al45tair

Reputation: 4433

If you check the documentation, you'll see that, as the error says, +stringWithContentsOfFile: is deprecated. The reason is that there is no error indication and it doesn't specify which encoding to use.

You could change the third line to something like

var error = NSError?
let dico = NSString(contentsOfFile:path, usedEncoding:NSUTF8StringEncoding, error:&error)

Noting that dico might be nil, in which case you should inspect error to see what went wrong.

(Also, in an ideal world, you should use the URL-based APIs in preference to the path-based ones. The path APIs aren't deprecated yet, but I suspect in the long run they will be.)

Upvotes: 2

Related Questions