有点难以解释,但如果达到一定条件,我需要停止我的程序。这是我使用的简化代码
func getNotificationData() {
NetworkingService.fetchJSON(url: url, methodUsed: .post, parameters: parameters) { (result) in
switch result {
case .failure:
// show alert error
case .success(let jsonFromServer):
let json = jsonFromServer as! JSON
let validity = json["valid"].intValue
if validity == 0 {
// show alert
} else if validity == 1 {
guard let dataNotification = json["data"].arrayObject as? [[String:Any]] else {return}
self.notificationData = dataNotification
self.notificationData = nil <--- HARD CODED to test empty data
print("xxx")
guard let notificationData = self.notificationData else {
print("bbbbbb")
self.noNotificationLabel.isHidden = false
self.tableView.isHidden = true
SVProgressHUD.dismiss()
return
}
if notificationData.isEmpty {
self.noNotificationLabel.isHidden = false
self.tableView.isHidden = true
SVProgressHUD.dismiss()
return
}
print("yyyyy")
self.thereIsAnError = false
print("zzzz")
}
}
}
}
我想重构我的代码以提高可读性。我想将上面代码的某些部分移动到类似下面代码的函数
func checkIfNotificationIsAvailable() {
guard let notificationData = notificationData else {
print("bbbbbb")
noNotificationLabel.isHidden = false
tableView.isHidden = true
return
}
if notificationData.isEmpty {
noNotificationLabel.isHidden = false
tableView.isHidden = true
return
}
}
所以我希望我的结束代码会像这样
func getNotificationData() {
NetworkingService.fetchJSON(url: url, methodUsed: .post, parameters: parameters) { (result) in
switch result {
case .failure:
// show alert error
case .success(let jsonFromServer) :
let json = jsonFromServer as! JSON
let validity = json["valid"].intValue
if validity == 0 {
// show alert
} else if validity == 1 {
guard let dataNotification = json["data"].arrayObject as? [[String:Any]] else {return}
self.notificationData = dataNotification
self.notificationData = [] <--- HARD CODED to test empty data
print("xxx")
self.checkIfNotificationIsAvailable()
print("yyyyy")
print("zzzz")
}
}
}
}
但如果在重构后运行应用程序,则在调试区域中将打印
我希望yyyy和zzzz不会被打印,换句话说我的程序会在打印后排出{&#34; bbbbb&#34;),行if notificationData.isEmpty
,所以如何停止程序为了阻止执行print("yyyy")
和print("zzzz")
?我认为可以使用return
来完成,但它仍会执行checkIfNotificationIsAvailable()
下面的代码
答案 0 :(得分:1)
更改
case .back:
backButton.imageView?.image = #imageLiteral(resourceName: "arrow_left")
break
返回Bool
func checkIfNotificationIsAvailable() {
...
}
并在函数func getNotificationData(){..}
中更改
func checkIfNotificationIsAvailable() -> Bool{
guard let notificationData = notificationData else {
print("bbbbbb")
noNotificationLabel.isHidden = false
tableView.isHidden = true
return true
}
if notificationData.isEmpty {
noNotificationLabel.isHidden = false
tableView.isHidden = true
return false
}
return true
}
到
self.checkIfNotificationIsAvailable()