Jeff A Jeff A - 7 months ago 11
Swift Question

How to add an Array<String> to a Dictionary<String, AnyObject> in Swift 2

I'm trying to create a JSON object to use for my backend using Alamofire. I am able to add a key with a String value but can't seem to be able to add a value of Array to AnyObject. I though it would be very straight forward but I haven't been able to find a solution.

func someFunction(btn: UIButton){

var someDictionary = Dictionary<String, AnyObject>()
let someArray = [textField[1].text,textField[2].text,textField[3].text]
someDictionary["answer"] = textField[0].text
someDictionary["options"] = someArray as? Array // <---- Can't be assigned to AnyObject

let url = "http://localhost:3000/api/question"
Alamofire.request(.POST, url, parameters: someDictionary).responseJSON { response in
if let JSON = response.result.value as? Dictionary<String, AnyObject>{
}
}

}


Solution: Removed
as? Array
and created loop to append initialized Array

func someFunction(btn: UIButton){



var someDictionary = Dictionary<String, AnyObject>()
var SomeArray = [String]()
for i in 1...3{ //created loop to append the textField text
SomeArray.append(textField[i].text!)
}
someDictionary["answer"] = textField[0].text
someDictionary["options"] = SomeArray // Removed "as? Array"
let url = "http://localhost:3000/api/question"
Alamofire.request(.POST, url, parameters: someDictionary).responseJSON { response in
if let JSON = response.result.value as? Dictionary<String, AnyObject>{
print("JSON Response From Server-->\(JSON)")


}
}

}

Answer

Clean your project and run again. Your code is working for me and I can assign

func someFunction(btn: UIButton){

    var someDictionary = Dictionary<String, AnyObject>()
    let someArray = ["SomeString","SomeString","SomeString"]
    someDictionary["answer"] = textFields[0].text
    someDictionary["options"] = someArray // now you can assign

    let url = "http://localhost:3000/api/question"
    Alamofire.request(.POST, url, parameters: someDictionary).responseJSON { response in
        if let JSON = response.result.value as? Dictionary<String, AnyObject>{
        }
    }

}