Swift从功能完成中获取值,并将其设置为全局变量



我正在尝试从函数上获取竞争的变量,并将其变成全局变量。这是我正在调用的功能:

func getJsonFromUrl(name: String, completion: @escaping (String?)->()) {
//use name variable just as you would in a normal function
let URL2 = "https://url.com/asd.php"
let url = URL(string: URL2)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
    if error != nil {
        print(error as Any)
        completion(nil)
    } else {
        do {
            guard let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any] else { completion(nil); return }
            guard let ips = parsedData["ip"] as? String else {completion(nil); return }
            print("The IP is: " + ips) //Prints the value correctly
            completion(ips)
        } catch let error as NSError {
            print(error)
            completion(nil)
        }
    }
}.resume()
}

这就是我称之为:

 getJsonFromUrl(name: "Bob", completion: { ips in
            print(ips)
        })

但是,我想将IPS从称为全局变量的位置转动。当前,我在ViewController之外有一个名为IP2的变量,这就是我尝试设置变量的方式:

 getJsonFromUrl(name: "Bob", completion: { ips in
            print(ips)
            ip2 = ips!
        })

,它没有将IP2设置为IP的值。你怎么做?

我认为问题是因为urlsession是异步任务。尝试一下可能会有所帮助:

更改定义ip2变量的方式:

var ip2 : String = "" {
    didSet {
       //Do something when ip2 get the value
    }
}

相关内容

  • 没有找到相关文章

最新更新