异常处理
swift2.0新添加了异常处理机制,使swift更加安全,提高了代码的可读性
关键字
throws、throw、try、do、catch
实例
一个简单的用户登录实例,用异常处理机制来优化登陆
简单布局一下,两个textfield,一个button,和代码关联一下
@IBOutlet weak var usertf: UITextField!
@IBOutlet weak var passtf: UITextField!
@IBAction func loginAction(sender: UIButton) {
log()
}
创建一个字典用来验证用户密码
let dic = ["songyi":"123456"]
定义登陆异常枚举,自定义异常枚举要遵循ErrorType协议
enum loginError:ErrorType{
case Nouser(message:String) //未输入用户名
case Nopasswd(message:String) //为输入密码
case passwrong(message:String) //密码错误
}
创建登陆方法
func log(){
}
在log方法后 面添加throws关键字
func log() throws{
//添加throws关键字,如果该方法产生异常,则向上抛出异常
guard usertf.text != "" else{
throw loginError.Nouser
}
guard passtf.text != "" else{
throw loginError.Nopasswd
}
guard dic[usertf.text!] == passtf.text! else {
throw loginError.passwrong
}
}
在按钮点击事件中点击调用log方法
@IBAction func loginAction(sender: UIButton) {
do{
try log() // 如果密码正确行下执行
alert("成功", message: "登陆成功")
}catch loginError.Nouser{
alert("失败", message:"未输入用户名")
}catch loginError.Nopasswd{
alert("失败", message: "未输入密码")
}catch loginError.passwrong{
alert("失败", message: "密码错误")
}catch{
alert("失败", message: "其他错误")
}
}
定义提示框方法
func alert(title:String,message:String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(cancel)
self.presentViewController(alert, animated: true, completion: nil)
}
完整代码
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var usertf: UITextField!
@IBOutlet weak var passtf: UITextField!
let dic = ["songyi":"123456"]
enum loginError:ErrorType{
case Nouser //未输入用户名
case Nopasswd //为输入密码
case passwrong //密码错误
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginAction(sender: UIButton) {
do{
try log()
alert("成功", message: "登陆成功")
}catch loginError.Nouser{
alert("失败", message:"未输入用户名")
}catch loginError.Nopasswd{
alert("失败", message: "未输入密码")
}catch loginError.passwrong{
alert("失败", message: "密码错误")
}catch{
alert("失败", message: "其他错误")
}
}
func alert(title:String,message:String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(cancel)
self.presentViewController(alert, animated: true, completion: nil)
}
func log() throws{
guard usertf.text != "" else{
throw loginError.Nouser
}
guard passtf.text != "" else{
throw loginError.Nopasswd
}
guard dic[usertf.text!] == passtf.text! else {
throw loginError.passwrong
}
}
}