0

I am trying to send some data from an array to an other interfaceController. The problem is that I am getting

unexpectedly found nil while unwrapping an Optional value exception

even though the array is not nil. In fact I can even print the result using

print(...).

the problem is that I cannt set this result to a label without getting the exception.

Here is my code to laugh the new interfaceController with context data

@IBAction func lauchInterfaceClick() {

    presentControllerWithName("SecondInterface", context: ["hi","how are you"])

}

And then retrieve the results in SecondInterface like below

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    // Configure interface objects here.
    if context != nil{

        let somevalue = context as! [String]

        // here is where I getting the exception, in addition to Thread 1: EXC_BAD_INSTRUCTION (code=EXC_i386_INVOP, subcode=0x0)
        self.showWat.setText(String(somevalue[0]))

        // I have also tried this
        // self.showWat.setText(somevalue[0])

    } 

please note that on the other hand a print(String(somevalue[0])) outputs hi

olympia
  • 362
  • 2
  • 20
hight
  • 21
  • 4
  • try printing `somevalue ` – Bista Jan 19 '16 at 11:11
  • 2
    there are a million questions here on SO about this error, are you sure none of them offer you a solution? – Hamish Jan 19 '16 at 11:14
  • 3
    You're getting the error because `showWat` is nil, not the array. – Cihan Tek Jan 19 '16 at 11:19
  • @aaisataev showWat is a WKInterfaceLabel, – hight Jan 19 '16 at 17:26
  • @CihanTek how is it possible? showWat is a WKInterfaceLabel.. How could I fix it then – hight Jan 19 '16 at 17:28
  • @originaluser2 unfortunately I haven' t one where even though the value is there there is still an error.. all of them are more or less similar.. in their case the value passed is nil but in my case this value is not nil – hight Jan 19 '16 at 17:31
  • sorry guys ..I found out that I disconnected the wkInterfaceLabel to the label in the interfaceController... – hight Jan 19 '16 at 22:06

1 Answers1

0

I would use an implementation of awakeWithContext(context: AnyObject?) like this:

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    // Configure interface objects here.
    if context != nil{

        let somevalue = context as? [String] {
            if somevalue.count > 0 {
                let text = somevalue[0]
                showWat.setText(text)
            }


        } else {

            // Unwrapped optional is nil
            print("someValue is nil!")
        }

    }
}

Checkout the section 'Optional Chaining as an Alternative to Forced Unwrapping' in the Swift Programming Language Reference.

Or checkout this answer here on Stack overflow.

Community
  • 1
  • 1
Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44