Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Swift Dictionary to NSDictionary

Tags:

swift

I have created a Swift Dictionary object

var params = ["first_name": firstNameTextField.text,
              "last_name": lastNameTextField.text,
              "company": companyTextField.text,
              "email_address": emailTextField.text,
              "phone_number": phoneTextField.text]

Next, I have ObjC framework which I connected to my Swift app. There is an object inside with property

@property (nonatomic, retain) NSMutableDictionary *fields;

I'm trying to assign it this way

object.fields = params

And got an error:

Cannot convert the expression's type '()' to type 'NSMutableDictionary!'

I also tried to do it this way

var params = ["first_name": firstNameTextField.text,
              "last_name": lastNameTextField.text,
              "company": companyTextField.text,
              "email_address": emailTextField.text,
              "phone_number": pnoneTextField.text].mutableCopy() as NSMutableDictionary

object.fields = params

It compiled well, but I got runtime error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: 
attempt to insert nil object from objects[0]'

I have all my fields printed and they aren't nil:

println(firstNameTextField.text)
println(lastNameTextField.text)
println(companyTextField.text)
println(emailTextField.text)
println(pnoneTextField.text)

...

1
2
3
5
4

Any ideas?

like image 424
Rubycon Avatar asked Jun 11 '14 20:06

Rubycon


2 Answers

Try parms.bridgeToObjectiveC(). That may give you an NSDictionary rather than an NSMutableDictionary, though.

like image 78
Bill Avatar answered Oct 16 '22 22:10

Bill


I'm guessing that this code initializing your params...

var params = ["first_name": firstNameTextField.text,
              "last_name": lastNameTextField.text,
              "company": companyTextField.text,
              "email_address": emailTextField.text,
              "phone_number": phoneTextField.text]

...might be happening before you have any text field outlets hooked up. What I would suggest is that you set this var as @lazy, type it as Dictionary<String,String>, and set it to a called closure that returns this dictionary. Thus the dictionary won't be created until later, when you actually access self.params.

like image 34
matt Avatar answered Oct 16 '22 21:10

matt