1

Im currently working on an iOS app that requires the parsing of a dictionary of words.

When I attempt to import the file and convert the contents to Strings I get an error on the let path:String = Bundle.main.path(forResource: "words", ofType: "txt")! line. The error is Thread 1: "EXC_BREAKPOINT(code=1,subcode=0x1002e11ec)"

Any help would be greatly appreciated.

NOTE: Screen shot of assets attached

let path:String = Bundle.main.path(forResource: "words", ofType: "txt")!
text =  try! String(contentsOfFile: path, encoding: String.Encoding.utf8)      
words  = text.components(separatedBy: ("\n"))

enter image description here

Luke Mann
  • 105
  • 1
  • 8

2 Answers2

2

Bundle path(forResource:ofType:) returns an optional String. You are force unwrapping the options. This crashes when the return value is nil.

It returns nil when there is actually no such file in your app's resource bundle.

  1. You need to actually have a file named words.txt in your app's bundle. Make sure the filename case matches and make sure the file is selected for your target.
  2. Generally you shouldn't force-unwrap optionals. It causes crashes. However, one can argue that the two force-unwraps in the code you posted will never crash once your app is working properly. The first one is only crashing because you have not yet properly put the file in your resource bundle. And the 2nd (try!) won't crash once your file is correct because you know it will be a valid text file in the given encoding.
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I like to tell people new to Swift: "Until you really understand optionals in Swift you should pretend that the `!` force-unwrap operator doesn't exist. – Duncan C Nov 22 '16 at 00:07
  • @rmaddy Thanks for the advice but it looks like the file is named properly. Do you have any you any other suggestions? – Luke Mann Nov 22 '16 at 00:13
  • 1
    I've never use a dataset in Xcode before so I have no idea how you are supposed to access such a file. Using `Bundle` is for files you have placed in your app's resource bundle. I'm not sure why you have your text file in a data set. – rmaddy Nov 22 '16 at 00:19
  • See http://stackoverflow.com/questions/27206176/where-to-place-a-txt-file-and-read-from-it-in-a-ios-project – rmaddy Nov 22 '16 at 00:20
0

Don't use a dataset. Just drag your txt file right into the file navigator.

enter image description here

To explain further, the error you're seeing is that you're using ! which says you're guaranteeing that a path for that resource exists in the bundle. Which it doesn't.

Frankie
  • 11,508
  • 5
  • 53
  • 60