如何快速将两个值中的一个值添加到参数键?

时间:2020-08-16 10:09:25

标签: json swift dictionary button

我的AddEventViewController包含两个按钮1)PublishEvent 2)DraftEvent

在这里,如果我单击publisheventBtn,则事件应显示在发布段中。如果我单击DraftDtn,则事件应转到草稿段

为此,我具有如下所示的JSON参数:这里如何根据buttonclick更改status键值意味着如果我单击PublishEvent,那么我必须给出status = "Publish",如果我单击草稿,然后单击status = "Draft"

let parameter = ["status":"Draft", "eventName": eventNameField.text, "eventMessage": msgTextfild.text, "eventDate": Fromdate, "eventTime": fromTime, "eventEndDate": Todate, "eventEndTime": toTime, "isAllDayEvent":"false", "isEventRepeatable":"false"] as [String : Any]

剩余代码:

func AddEvent(){

let request = NSMutableURLRequest(url:url! as URL,
                                  cachePolicy: .useProtocolCachePolicy,
                                  timeoutInterval: 10.0)
request.httpMethod = "POST"
        if httpResponse!.statusCode == 200 {
            do {
                let jsonObject  = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String :AnyObject]
               let viewController = self.storyboard?.instantiateViewController(withIdentifier: "EventsViewController") as! EventsViewController
                viewController.eventType = "Published"
                self.navigationController?.pushViewController(viewController, animated: true)
                }
            }
            catch  {
                print(error.localizedDescription)
            }
        }
        else {
            self.showAlert(title: "", message: "Please enter vaild details")
        }
    }
})
dataTask.resume()
}


@IBAction func publishNewEvent(_ sender: Any) {

    addNewEvents()
}
@IBAction func draftEvent(_ sender: Any) {

addNewEvents()
}

1 个答案:

答案 0 :(得分:1)

您可以使用三元运算符?将值分配给status变量,然后根据条件为其分配适当的值。

let status = didClickDraftButton ? "Draft" : "Publish"
let parameter = ["status": status, ...]

相应地设置didClickDraftButton的值。这是一个示例:

var didClickDraftButton = true // default value or could use optional if you want

@IBAction func publishNewEvent(_ sender: Any) {
    didClickDraftButton = false
    addNewEvents()
}
@IBAction func draftEvent(_ sender: Any) {
    didClickDraftButton = true
    addNewEvents()
}