1

I'm attempting to set a text label string value equal to the text field string value. However, it is crashing due to a unexpectedly found nil while unwrapping an optional value. I thought that nil-coalescing will work just fine in a macOs application. Any idea what would be the proper way to handle this error?

At the moment, I have tried to nil-coalescing to make sure that the default value is a blank string.

@IBAction func textFunctionality(_ sender: NSButton) {
    let text: String = textField.stringValue ?? ""
    switch sender.tag {
    case 0:
        print(textLabel.stringValue)
        textLabel.stringValue = text
    default:
        print("error")
    }
}

I expect to set the text label string value to the text field string value. For example, if the string value of the text field is Adam, then string value of the text label will be Adam as well.

NTaveras
  • 73
  • 1
  • 8
  • Change print(textLabel.stringValue) to print(text) – Darrell Root Feb 15 '19 at 15:09
  • @DarrellR The error occurs on this line: let text: String = textField.stringValue ?? "" – NTaveras Feb 15 '19 at 15:26
  • Ok, got it and duplicated in a playground. This fails: let text: String = textField.stringValue ?? "" But this succeeds: let text: String = textField?.stringValue ?? "" The problem is that you are sending the stringValue message to the object textField which is nil. You need to put a ? after textField to allow the message to not be sent if textField is nil. Of course that will result in the result being nil at which point your nil-coalescing operator takes over and creates a blank (but non-nil) text final result. – Darrell Root Feb 15 '19 at 16:25

0 Answers0