0

i'm going nuts.

I'm trying to get the list of "txt" files from a folder but i get the list in the form of

Optional("Filename").txt

Here's my code, nothing fancy. I tried unwrapping the filename but the compiler gives me an error.I tried a "guard", a with "if", i tried "!" ... nothing works.

   let enumerator:FileManager.DirectoryEnumerator = FileManager().enumerator(atPath: myFolderPath)!

    while let element = enumerator.nextObject() as? String {

        print(element)

        if element.hasSuffix("txt") {

            fileList.append(element)
        }

    }

I need to show this list in a table view.

I hope i'm not supposed to run trought the array and get the name of the files by using a bunch o string methods just to get rid of this text...

I'm not sure what can i do! I don't really want to use this solution:

Swift: Optional Text In Optional Value

Thank you

Community
  • 1
  • 1
donio20
  • 75
  • 6
  • 3
    You should look at the files in that folder and make sure you don't have a file with that name. I wonder if you neglected to unwrap an optional when originally building the filename when you were creating the file. If running this on the simulator, on your Mac Finder, navigate to `~/Library/Developer/CoreSimulator/Devices`, find the one for your device that you're testing on (look at modify dates rather than relying upon those cryptic UUIDs). – Rob Nov 23 '16 at 20:53
  • 1
    Unrelated to the problem at hand, rather than `FileManager()`, I'd suggest `FileManager.default`, e.g. `let enumerator = FileManager.default.enumerator(atPath: myFolderPath)!`. – Rob Nov 23 '16 at 20:57
  • The code is supposed to work. Have you declared `fileList` as `[String?]`? If yes don't do that. – vadian Nov 23 '16 at 20:58
  • @vadian If that were the case, it would say `Optional("Filename.txt")`, not `Optional("Filename").txt`. Or maybe he made a mistake typing the question... – Rob Nov 23 '16 at 21:00
  • 1
    @Rob Yes that's true. Personally I would prefer the modern URL related API anyway – vadian Nov 23 '16 at 21:02
  • 2
    What files are you looking for? Could it be that you have accidentally saved the files with the name `Optional("Filename").txt` yourself, that the bug is rather in the code *saving* the files than in the code *enumerating* them? Your code runs just fine in iOS playground. – Codo Nov 23 '16 at 21:51

1 Answers1

0

@ Vadian and Rob: you guys rock, you asked the right question.

The issue was that i'm naming the .txt files with a textfield and i'm doing all the necessary work to make sure that this textfield is not empty or otherwise.

I never thought that this textfield could be optional, hence the Optional("Filename").txt

Once i unwrapped the value from the textfield Optional() had gone.

Thank you.

donio20
  • 75
  • 6