0

I am trying to read a .txt file from my Resource folder in a swift iOS project. The function is

class func readFile(){
        var filePath = NSBundle.mainBundle().pathForResource("testfile", ofType:"txt")
        var dataout = NSString(contentsOfFile: filePath!, encoding: NSUTF8StringEncoding, error: nil)
        println(dataout)
    }

My text file is

This is a test

The console outputs

Optional(This is a test )

I can't figure out what the Optional() is????

NJGUY
  • 2,045
  • 3
  • 23
  • 43
  • That doesn't explain why it is printing out 'Optional(...)' – NJGUY Oct 27 '14 at 03:43
  • 1
    That's just the `println` (`Printable` protocol really) representation of an optional value. If you unwrap the value first, it won't print the `Optional()` part. – Mike S Oct 27 '14 at 03:44
  • [you can look at this question](http://stackoverflow.com/questions/25926536/read-text-file-in-swift/26581039#26581039) – Leo Dabus Oct 27 '14 at 04:23
  • var dataout = String(contentsOfFile: filePath!, encoding: NSUTF8StringEncoding, error: nil)! // try it like this and the answer for your question: optional means that you might get an error/nil or a string returned when trying to read it – Leo Dabus Oct 27 '14 at 05:32

0 Answers0