[NSObject:AnyObject]!和joinWithSeparator

时间:2015-11-17 13:28:56

标签: swift facebook-sdk-4.0

如何在以下函数中从结果(Dictionary)中获取字符串值(joinWithSeparator)?

func gameRequestDialog(gameRequestDialog: FBSDKGameRequestDialog!, didCompleteWithResults results: [NSObject : AnyObject]!){
        NSLog("resoult.count: %i", results.count)
        let res = results["to"] // This is a Key Value par
        let res = results["to"] as Dictionary // Error: has no subscript members
        let res = results?["to"] as Dictionary // Error: Value of optional type 'AnyObject' not unwrapped.


...

结果包含:

([NSObject : AnyObject]!) results = 5 key/value pairs {
  [0] = {
    key = 0x000
    value = 0x000
  }
  [1] = {
    key = 0x000
    value = 0x000
  }
  [2] = {
    key = 0x000
    value = 0x000
  }
  [3] = {
    key = 0x000
    value = 0x000
  }
  [4] = {
    key = 0x000
    value = 0x000
  }
}

我正在寻找像res.joinWithSeparator(",")这样的东西来获取带有值的字符串。

提前致谢

1 个答案:

答案 0 :(得分:0)

我会对Dictionary进行扩展,以获取包含所有值的String。

这样的事情:

extension Dictionary {
    var joinedValues:String {
        return self.values.map { String($0) }.joinWithSeparator(", ")
    }
}

用法示例:

let dict = ["name":"Mike", "age":42, "gender":"male"]

let valuesAsString = dict.joinedValues  // "male, 42, Mike"

当然,只有当您的值可以转换为String()的字符串时,它才会起作用。如果没有,则必须根据值的类型进行特定扩展。