以下是其中的代码,如果userNameTF或passwordTF已满或为空,则会显示警报。
@IBAction func LoginBtn(sender: AnyObject) { let userName = userNameTF.text let password = passwordTF.text if ((userName?.isEmpty) != nil) { displayMyAlertMessage ("Forget to fill your user name") return } if ((password?.isEmpty) != nil){ displayMyAlertMessage ("Forget to fill your password") return } } func displayMyAlertMessage(userMessage:String){ let myAlert = UIAlertController(title: "WOF", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) myAlert.addAction(okAction) self.presentViewController(myAlert, animated: true, completion: nil) }
这是一个很好的例子 guard
guard
@IBAction func LoginBtn(sender: AnyObject) { guard let userName = userNameTF.text where !userName.isEmpty else { displayMyAlertMessage ("Forget to fill your user name") return } guard let password = passwordTF.text where !password.isEmpty else { displayMyAlertMessage ("Forget to fill your password") return } // do something with userName and password }