Search code examples
variablesswiftalertview

Swift Error while trying to print variable from alert-view textfield


I have this code here that runs an alertview and shows a textfield asking for the subject name

 alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler:{ (alertAction:UIAlertAction!) in
            var textf= alertController.textFields[0] as UITextField
            self.items += [self.textf]
            println(self.items)
            println(textf)
            self.view .setNeedsDisplay()

        }))

And then Im declaring the variables items and textf out of that function at the top of the code using this code

var items = ["English"]
let textf = ""

but the problem is that when I run my app and click on my button that shows the alertview and i type in my subject and click ok I get this error when it tries to print out string. It just prints out this error and it does not close my app

<_UIAlertControllerTextField: 0x7f9d22d1c430; frame = (4 4; 229 16); text = 'irish'; clipsToBounds = YES; opaque = NO; gestureRecognizers = <NSArray: 0x7f9d22cc55f0>; layer = <CALayer: 0x7f9d22d1c6e0>>

It says in the error the text I typed in but It is not adding it to the variable because when i print out the array items it prints out

[English, ]

and not

[English, irish]

Solution

  • This is weird...

    var textf= alertController.textFields[0] as UITextField
    self.items += [self.textf]
    

    var textf and self.textf are two different variables. It looks like self.textf is the empty string you set outside your function. So an empty string is what's getting added to the items array.

    You also have another problem. You seem to want a string, but your var textf value is a UITextField. You need to snag the text property if you wan the string.

    This confusion is why I like explicit typing. If you are expecting a String and have a UITextField the compiler will catch that if you explicitly type your variables.

    Which means you need something more like this:

    var items: [String] = ["English"]
    var textf: UITextField? = nil // this variable optionally holds a text field
    
    // later, inside some function...
    func somefunc() {
        alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler:{ (alertAction:UIAlertAction!) in
            self.textf = alertController.textFields[0] as UITextField
            // append() is preferable to += [], no need for a temporary array
            self.items.append(self.textf!.text)
            println(self.items)
            println(textf)
            self.view.setNeedsDisplay()
        }))
    }