如何在swift中获得这样的输出

时间:2017-03-31 09:47:51

标签: swift nsdictionary

{length = 30,contents =“something”,count = 32.3}

我需要此括号中的确切输出{}不在()或[]

var array:Array<Any> = Array<Any>();
array.append(NSDictionary(object: singleItem.name, forKey: "name" as NSCopying));
array.append(NSDictionary(object: singleItem.planned_revenue, forKey: "planned_revenue" as NSCopying));
array.append(NSDictionary(object: singleItem.phone, forKey: "phone" as NSCopying));
array.append(NSDictionary(object: singleItem.description, forKey: "description" as NSCopying));
array.append(NSDictionary(object: singleItem.email_from, forKey: "email_from" as NSCopying));
 array.append(NSDictionary(object: singleItem.probability, forKey: "probability" as NSCopying));

输出

[{
    name = "this is another";
}, {
    "planned_revenue" = "0.0";
}, {
    phone = "";
}, {
    description = "Internal Notes";
}, {
    "email_from" = "thomas.passot@agrolait.example.com";
}, {
    probability = "20.0";
}]

我需要像

[{ name = "this is another", "planned_revenue" = "0.0", phone = "", description = "Internal Notes", ..... }]

1 个答案:

答案 0 :(得分:2)

首先,您需要一个字典,而不是一个字典数组。使用Swift,您可以使用Dictionary代替NSDictionaryDictionary<String, Any>[String: Any]):

let dict: [String: Any] = [
    "name": singleItem.name,
    "planned_revenue": singleItem.planned_revenue,
    "phone": singleItem.phone,
    "description": singleItem.description,
    "email_from": singleItem.email_from,
    "probability": singleItem.probability
]

// If you need a NSDictionary, you can cast it
let nsDict = dict as NSDictionary

请查看Collection Types in the Swift guideDictionary class reference以获取更多信息。