-2

I have the below logic in the program

var keerthanaiArray:[KStruct]!

if KeerthanaigalDB.open()
    {
        var i = 0
        let querySQL = "SELECT * FROM KEERTHANAIGAL ORDER BY ROWID DESC"
        let results:FMResultSet? = KeerthanaigalDB.executeQuery(querySQL, withArgumentsInArray: nil)
        if (results != nil)
        {
            while results!.next()
            {

               let songTitleT = results?.stringForColumn("SONGNAME") as String!
                arrayData1.append(songTitleT!)
                let songLyricsT = results?.stringForColumn("SONGLYRICS") as String!
                arrayData2.append(songLyricsT!)
                let EsongTitleT = results?.stringForColumn("ESONGNAME") as String!

                print(songTitleT)
                keerthanaiArray.append(KStruct(SongTitle : songTitleT!, SongLyrics : songLyricsT!,
                    ESongTitle : EsongTitleT!))

when I tried to execute the last statement keerthanaiArray.append the code breaks and throws an error message fatal error: unexpectedly found nil while unwrapping an Optional value

Please help

Jebus
  • 9
  • 5
  • Probably reason: `keerthanaiArray` is `nil` because you never assigned an array to it. `var keerthanaiArray:[KStruct] = []` would solve *that* problem. – But you really should try to get rid of all the implicitly unwrapped optionals and forced unwrapping. I have the feeling that you inserted them to just make it compile. Try to understand whether a variable can be nil or not, and use optionals where necessary. – Martin R Jul 30 '16 at 19:39
  • 1
    A good read is [When should I compare an optional value to nil?](http://stackoverflow.com/questions/29717210/when-should-i-compare-an-optional-value-to-nil) and [What does “fatal error: unexpectedly found nil while unwrapping an Optional value” mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Martin R Jul 30 '16 at 19:41
  • yes it works. thanks a lot – Jebus Jul 30 '16 at 19:55

1 Answers1

0

Well of course it crashes. You make keerthanaiArray an implicitly unwrapped optional, and then never initialize it.

Until you understand optionals you should pretend the ! force unwrap operator does not exist. If you don't know what you're doing it is the crash operator.

For the line in question, you should be able to fix the problem by changing your variable definition to:

var keerthanaiArray = [KStruct]()

That makes it a non-optional array and initializes it right away, so the variable contains an empty array the first time you try to use it.

See this thread for a discussion of how to handle optionals and unwrapping:

What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?

Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272