首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从swift 4中的闭包中获取补全块外的变量的值

问从swift 4中的闭包中获取补全块外的变量的值
EN

Stack Overflow用户
提问于 2018-10-10 00:30:33
回答 1查看 554关注 0票数 1

我有一个用swift 4编写的项目,当我试图访问闭包内部的值时,它会产生nil。下面是我的代码:

代码语言:javascript
复制
import UIKit
import SwiftyJSON

class TchatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    var coach_ID: String!

    var responseArr = [JSON]()
    var responseInfo = [JSON]()

    var userIDS: String?
    var typeUsers: String?
    var chatID: String?
    var appdict: NSDictionary?

    @IBOutlet weak var tblMessage: UITableView!
    @IBOutlet weak var txtMsgs: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let userInfo = DataManager.sharedInstance.loadUser()
        getAvisList(user: userInfo!)

        tblMessage.delegate = self
        tblMessage.dataSource = self

        print("CoachIDS",coach_ID!)
    }

    func getAvisList(user: User) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let userId = user.id
        print("chatuserId",userId!)
        self.userIDS = userId
        let userType = Int(user.type!)
        print("chatusertype",userType!)

        // var url: String = ""

        self.typeUsers = user.type!

        let todosEndpoint: String = "http://testchat.com/api/chats/createChatroomMobile"

        let newTodo = ["user_type":userType!, "user_id":userId!,"coach_id":coach_ID!] as [String : Any]

        let loader = appDelegate.showLoading()
        WebServices.sharedInstance.post(toURL: todosEndpoint, withParams: newTodo, successHandler: { (jsonData) in
            print("chatroom data: \(jsonData)")
            // self.responseArr  = jsonData.arrayValue
            let responseInfo = jsonData.dictionaryValue
            let appdict = (responseInfo as Any as! NSDictionary).value(forKey: "chatroomID")!

            print("Chatroom==",appdict) // the value gets printed here.

            let strinDuration:NSString = NSString(format:"http://testchat.com/api/chats/room/id/%@",appdict as! CVarArg)  as String as String as NSString

            print("strinDuration ==",strinDuration)

            WebServices.sharedInstance.get(toURL: strinDuration as String, successHandler: { (jsonData) in
                print("ChatHistroy: \(jsonData)")

                self.responseArr  = jsonData.arrayValue
                self.responseArr = self.responseArr.reversed()
                self.tblMessage.reloadData()
                // I am getting this data for the table view.
            }) { (error) in
                print(error)
            }

            self.appDelegate.dismissLoading(loader)
        }) { (error) in
            print(error)
            self.appDelegate.dismissLoading(loader)
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // return self.avisList.count
        return self.responseArr.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200.0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: TChatCell = tableView.dequeueReusableCell(withIdentifier: "tchatcell") as! TChatCell

        let index = self.responseArr.count - indexPath.row - 1
        cell.descriptionMsg.text = self.responseArr[index]["message"].stringValue

        return cell
    }

    //Till here, it works fine. But below from here, the value gets nil.

    @IBAction func sendMessage(_ sender: Any) {
        let todosEndpoint: String = "http://testchat5479.ilovemydietcoach.com/api/chats/addMessage"

        print("self.userIDS",self.userIDS!) //It gives the value.
        print("self.typeUsers",self.typeUsers!) //It gives the value.
        print("self.chatID===", appdict)// The value of appdict is nil here.
    }
}

/我也为post和get方法编写了get服务的代码。

代码语言:javascript
复制
class WebServices: NSObject {

static let sharedInstance = WebServices()

func post(toURL urlString:String, withParams postParams:Parameters, successHandler: @escaping (( _ jsonData:JSON) -> Void), failureHandler: @escaping((_ error:Error) -> Void)) {
    let url = URL(string: urlString)!

    let headers = ["Accept":"application/json", "Content-Type":"application/json"]

    Alamofire.request(url, method: .post, parameters: postParams, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) -> Void in

        switch response.result {
        case .success(let value):
            let tempInfo = JSON(value)
            successHandler(tempInfo)
        case .failure(let error):
            failureHandler(error)
        }
    }

}
   func get(toURL urlString:String, successHandler: @escaping (( _ jsonData:JSON) -> Void), failureHandler: @escaping((_ error:Error) -> Void)) {
    let url = URL(string: urlString)!

    let headers = ["Accept":"application/json", "Content-Type":"application/json"]

    Alamofire.request(url, method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        switch response.result {
        case .success(let value):
            let tempInfo = JSON(value)
            successHandler(tempInfo)
        case .failure(let error):
            failureHandler(error)
        }
    }

}

}

appdict在之前的闭包中有一些值,但在这里是空的。我必须在这里使用appdict的值。我如何在swift 4中解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2018-10-10 00:36:20

当你在闭包中赋值给appdict时,你通过使用let来隐藏你的成员变量:

代码语言:javascript
复制
let appdict = (responseInfo as Any as! NSDictionary).value(forKey: "chatroomID")!

使用let,您可以创建一个局部变量来隐藏成员appdict。如果你删除了let,你将赋值给成员变量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52725520

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档