无法将类型[NSObject:AnyObject]转换为字符串

时间:2016-03-21 07:46:50

标签: ios swift

我使用Xcode 7.2在Swift中使用此代码。

func silentPostData(serverName: String, serverport serverPort: String, serverurl serverURL: String, parameters: [NSObject : AnyObject], urldata urlData: NSData) {
    let persist = Persistence()
    var finalURl = "https://\(serverName):\(serverPort)/\(serverURL)"
    for key : String in parameters  {
        finalURL = finalURL.stringByAppendingString(key)
        finalURL = finalURL.stringByAppendingString("=")
       finalURL = finalURL.stringByAppendingString((parameters[key] as! String))
        finalURL = finalURL.stringByAppendingString("&")
    }
}

我在“for key:String in parameters {”行中收到错误(在标题中提到)。基于之前的答案'(NSObject, AnyObject)' is not convertible to 'String',我尝试将其转换为NSString,但它没有用。所以任何人都知道如何将[NSObject:AnyObject]转换为字符串?提前谢谢。

1 个答案:

答案 0 :(得分:1)

就像评论所说的那样,它是一本字典,你可以通过这样做来获得字符串:

parameters.keys.flatMap { $0 as? String }.forEach {
    finalURL = finalURL.stringByAppendingString($0)
    finalURL = finalURL.stringByAppendingString("=")
    finalURL = finalURL.stringByAppendingString(parameters[$0] as? String ?? "")
    finalURL = finalURL.stringByAppendingString("&")
}