简体   繁体   English

类型“字符串”不符合协议“ NSCopying”-数组swift json错误

[英]Type 'String' does not conform to protocol 'NSCopying' - Array swift json Error

sorry in advance for my bad english. 预先对不起我的英语不好。 I have a problem with my Swiftcode, i'm new in Swift so maybe you can help me :) 我的Swiftcode有问题,我是Swift的新手,所以也许您可以帮我:)

Here is my Code. 这是我的代码。

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in

        if(error != nil)
        {
            println("error\(error)")
            return;
        }

        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary

        if let parseJSON = json
        {
            var resultValue:String = parseJSON["message"] as String!;
            println("result: \(resultValue)")
            self.LabelFalscheEingabe.text = "\(resultValue)";

            if(resultValue == "Success")
            {
             var Projects:Array = parseJSON["projects"] as Array!; // here is the Error
            }
        }
        task.resume()
    }

'projects' is a variable from type Array on the server, so i want to get it as Array from the server, but if I try this i get the following error. 'projects'是服务器上Array类型的变量,因此我想从服务器上将其作为Array获取,但是如果我尝试这样做,则会收到以下错误。

Error: "Type 'String' does not conform to protocol 'NSCopying'". 错误:“类型'String'不符合协议'NSCopying'”。

Thanks in advance :) 提前致谢 :)

Your Projects array can't be declared like that, Swift has to know the type of the objects in the array. 您的Projects数组不能这样声明,Swift必须知道数组中对象的类型

If you don't know the type, then make it an array of AnyObject : 如果您不知道类型,则将其AnyObject数组:

if let Projects = parseJSON["projects"] as? [AnyObject] {
    // do something with Projects
}

If you know it's an array of Strings, for example: 如果您知道它是一个字符串数组,例如:

if let Projects = parseJSON["projects"] as? [String] {
    // do something with Projects
}

An array of Integers: 整数数组:

if let Projects = parseJSON["projects"] as? [Int] {
    // do something with Projects
}

An array of dictionaries made from JSON: 由JSON制成的字典数组:

if let Projects = parseJSON["projects"] as? [[String:AnyObject]] {
    // do something with Projects
}

Etc. 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM