Reputation: 1199
While I am trying to add a value to a dictionary, it always fail while I try to set the value from my textField.text. I have a text field, that I want to add to a dictionary, with this code:
var dict = [String:AnyObject]()
dict.updateValue(usernameText.text!, forKey: "key")
print(dict["key"]!)
However, on the print it doesn't show anything. When I am setting the value as "a value" - it prints fine. How come I can't add a text field value?
Upvotes: 1
Views: 1044
Reputation: 42143
What type is usernameText ? and are you certain that there is any text in it ?
try adding print(usernameText.text!) to make sure.
I tested with UITextField and could not reproduce the problem when there is text in the .text property.
Upvotes: 2
Reputation: 9662
Try it like this:
dict["key"] = usernameText.text!
Update:
Just tried this code:
var dict = [String:AnyObject]()
dict.updateValue("Foo", forKey: "key")
print(dict["key"]!)
and it prints me as I expected Foo
, try the following code, setting non optional value under "key"
key:
if let aText = usernameText.text {
dict.updateValue(aText, forKey: "key")
}
Upvotes: 0