如果语句输出两个参数而不是?

时间:2016-11-08 05:54:32

标签: ios json swift if-statement uiswitch

我有以下代码但不输出任何一个语句;两个语句都输出:

编辑:

经过大量的反复试验后,我仍然没有更接近解决方案,我已经将我的代码缩减到最低限度,并删除了所有其他控件以尝试解决此问题但仍然无效是我的最小代码附加到一个简单的单一开关:

//

导入UIKit

类ViewController:UIViewController {

@IBOutlet weak var mySwitch: UISwitch!
@IBAction func buttonClicked(_ sender: Any) {


    let switchOn = mySwitch.isOn
    let endpoint = "http://10.0.1.147/setpins"
    let urlString = endpoint + "?D2=" + (switchOn ? "0" : "1023")

    mySwitch.setOn(!switchOn, animated:true)

    var request = URLRequest(url: URL(string: urlString)!)
    request.httpMethod = "POST"
    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard error == nil else {
            print("error=\(error)")
            return
        }

        // You can print out response object
        print("response = \(response)")

    }
    task.resume()

}


}

但是:仍然在同一时间输出每个参数的输出..

response = Optional(<NSHTTPURLResponse: 0x17402d9e0> { URL: pttp://10.0.1.147/setpins?D1=0 } { status code: 200, headers {
    "Access-Control-Allow-Origin" = "*";
    Connection = close;
    "Content-Length" = 7;
    "Content-Type" = "text/plain";
} })

response = Optional(<NSHTTPURLResponse: 0x17002c8a0> { URL: pttp://10.0.1.147/setpins?D2=1023 } { status code: 200, headers {
    "Access-Control-Allow-Origin" = "*";
    Connection = close;
    "Content-Length" = 7;
    "Content-Type" = "text/plain";

2 个答案:

答案 0 :(得分:1)

在这种情况下,您实际上不需要if - else。这是您完全重写的代码 - 尝试运行它并查看重复问题是否消失。

let switchOn = mySwitch.isOn
switchState.text = switchOn ? "OFF" : "ON"
let endpoint = "http://10.0.1.147/setpins"
let urlString = endpoint + "?D2=" + (switchOn ? "0" : "1023")

mySwitch.setOn(!switchOn, animated:true)

var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { data, response, error in

    guard error == nil else {
        print("error=\(error)")
        return
    }

    // You can print out response object
    print("response = \(response)")

}
task.resume()

答案 1 :(得分:0)

尝试将task.resume移出if..else块以及其他声明。

//declare other variables here
if .... {
    ...
    ...
    ...
} else {
    ...
    ...
}

 let task = URLSession.shared.dataTask(with: request) { 
     (data: Data?, response: URLResponse?, error: Error?) in
         if error != nil{
             print("error=\(error)")
             return
         }
         // You can print out response object
         print("response = \(response)")
 }
 task.resume()