简体   繁体   中英

Cannot call value of non-function type '((UInt) -> Data?)!'

The following message show up when I convert swift 2 to swift 3 Cannot call value of non-function type ((UInt) -> Data?)!

func parseSJSON(_ data2: AnyObject) {      
    /** INITIALIZE THE SESSION **/
    clearUserInfo()
    if let data = data2.data(using: String.Encoding.utf8) {
        let json = JSON(data: data)
        let userID = json["userID"].stringValue
        prefs.setValue(userID, forKey: "userID")
    }
}

Thanks for your help, I try different approaches none of them work. And by try and error I change my code to this and it work!

func parseSJSON(_ data2: AnyObject, catalog:String) //func parseSJSON(_ data2: Data, catalog:String)

{

    clearUserInfo()
   // if let data = data2.data(using: String.Encoding.utf8) {

   if let data = data2.data(using: String.Encoding.utf8.rawValue) {
        let json = JSON(data: data)

        let userID = json["userID"].stringValue
        prefs.setValue(userID, forKey: "userID")
  }

}

You said

data2 is let object = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)

In that case, just pass that directly to JSON init method that takes the NSArray / NSDictionary , ie the rendition without data: parameter label:

let json = JSON(data2)    // note, if parameter is `Any` (the `NSDictionary`/`NSArray` structure of parsed JSON), then do not include `data:`

By the way, if you're going to parse it yourself like that, the .allowFragments is not needed, eg

let object = try JSONSerialization.jsonObject(with: data!, options: [])

Or, even easier, don't call JSONSerialization at all, and just pass the the Data directly:

parse(data: data!)

And let parse(data:) call JSON(data:) , which will parse it for you:

func parse(data: Data) {
    clearUserInfo()
    let json = JSON(data: data)     // note, if parameter is `Data`, include `data:`
    let userID = json["userID"].stringValue
    prefs.setValue(userID, forKey: "userID")
}

Previously you said data2 is a

Data / NSData that I received from http post

In that case, just cast it and don't use .data(using:) , eg

func parseSJSON(_ data2: AnyObject) {      
    ...

    if let data = data2 as? Data {
        // use `data` here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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