O.Naeem O.Naeem - 1 year ago 65
Swift Question

Swift: Why I am not able to execute the following if-statement when comparing two strings

So I am developing this app, where there is a textfield, and when you write on it, it is taken to the next SecondviewController. However, if nothing is written on the textfield and you press "Done" button, it should give you an error.

For this I have made an IBOutlet for the NSTextField as this:

@IBOutlet var weblinklabel: NSTextField!

Then this 'done' button contains an IBFunction with the following if statement:

@IBAction func actionWeblinklabel(_ sender: Any) {

if weblinklabel != "" {
} else {
label1.isHidden = false

Whatever is written in
should be compared with an empty string,
has something in it then it should just close the current viewController otherwise it should give me a label (label1).

When I do this, I get this error:

Binary operator '!=' cannot be applied to operands of type 'NSTextField!' and 'String'

What am I doing wrong with my code.
Thanks in advance! :)

Answer Source

The problem here is that you are comparing the NSTextField itself with the string "".

To access the text inside the NSTextField you must do weblinklabel.stringValue.