简体   繁体   English

无法将值类型“()”分配给字符串类型?

[英]Cannot assign value type '()' to type String?

I am just trying to get some information from a request using completionHandler.我只是想从使用 completionHandler 的请求中获取一些信息。 The thing is that I need the array with all the information from other part of the code and it seems I can't access to it.问题是我需要包含来自代码其他部分的所有信息的数组,但似乎我无法访问它。 Here it is where I access to the data:这是我访问数据的地方:

private func loadUserData(completionHandler: @escaping ([String]) -> ()) {
    // We're getting user info data from JSON response
    let session = Twitter.sharedInstance().sessionStore.session()
    let client = TWTRAPIClient.withCurrentUser()
    let userInfoURL = "https://api.twitter.com/1.1/users/show.json"
    let params = ["user_id": session?.userID]
    var clientError : NSError?
    let request = client.urlRequest(withMethod: "GET", url: userInfoURL, parameters: params, error: &clientError)
    client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
        if connectionError != nil {
            print("Error: \(connectionError)")
        }
        
        do {
            let json = JSON(data: data!)
            if let userName = json["name"].string,
                let description = json["description"].string,
                let followersCount = json["followers_count"].int,
                let favouritesCount = json["favourites_count"].int,
                let followingCount = json["friends_count"].int,
                let lang = json["lang"].string,
                let nickname = json["screen_name"].string {
                
                    self.userData.append(userName)
                    self.userData.append(description)
                    self.userData.append(String(followersCount))
                    self.userData.append(String(favouritesCount))
                    self.userData.append(String(followingCount))
                    self.userData.append(lang)
                    self.userData.append(nickname)
                
                    completionHandler(self.userData)
            }
        }
    }
}

func manageUserData(index: Int) {
    loadUserData() {_ in 
        return self.userData[index]
    }
}

And here it is where I need that data to show it:这就是我需要数据来显示它的地方:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let rowNumber = indexPath.row
    let cellIdentifier = "TableViewCell"
    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TableViewCellController else {
        fatalError("The dequeued cell is not an instance of TableViewCellController.")
    }
    
    switch rowNumber {
        case 0:
            cell.titlePlaceholder.text = "Name:"
            cell.valuePlaceholder.text = manageUserData(index: 1)

In this last line it's where the error occurs: "Cannot assign value of type '()' to type String?. I am not sure if I am using completionHandler properly in order to retrieve the data and ensure I can access to it from different parts of the code.在最后一行中,发生错误的地方是:“无法将 '()' 类型的值分配给 String 类型?我不确定我是否正确使用了 completionHandler 来检索数据并确保我可以从不同的部分代码。

Any idea ?有什么想法吗? Thank you very much!非常感谢!

UPDATE I was not using completionHandler properly.更新我没有正确使用completionHandler。 So I changed it by :所以我改变了它:

private func loadUserData(completion: @escaping (_ myArray: [String]) -> Void)

So my manageUserData function now looks like this:所以我的 manageUserData 函数现在看起来像这样:

func manageUserData() {
    loadUserData {
        (result: [String]) in
        self.secondUserData = result
    }
}

Hope this helps!希望这有帮助!

Since this is async network call, you should start this call in your VC's viewWillAppear , viewDidAppear , or viewDidLoad -- depending on if you need the data to reload.由于这是异步网络调用,您应该在 VC 的viewWillAppearviewDidAppearviewDidLoad启动此调用——这取决于您是否需要重新加载数据。

override func viewWillAppear(_ animate: Bool) {
    super.viewWillAppear(animate)
    sessionManager.loadUserData { (strings) in

    }
}

then inside of your loadUserData closure that will be ran whenever the call is complete, load the data into an array used as the tableView's datasource and call tableView.reloadData()然后在调用完成时将运行的loadUserData闭包内部,将数据加载到用作 tableView 数据源的数组中并调用tableView.reloadData()

sessionManager.loadUserData { (strings) in 
    self.dataSource = strings
    self.tableView.reloadData()
}

Then for your cellForRow you would just need:然后对于您的cellForRow您只需要:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let rowNumber = indexPath.row
    let cellIdentifier = "TableViewCell"
    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? TableViewCellController else {
        fatalError("The dequeued cell is not an instance of TableViewCellController.")
    }

    switch rowNumber {
        case 0:
            cell.titlePlaceholder.text = "Name:"
            cell.valuePlaceholder.text = dataSource[0]
    }
}

make sure your numberOfRows is returning dataSource.count确保您的numberOfRows正在返回dataSource.count

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

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