Error,throws和catch有什么用?

时间:2016-11-05 16:37:43

标签: ios swift

我正试图在swift中使用错误,例如我有这个代码:

import UIKit

class ViewController: UIViewController {

    enum SomeError: Error
    {
        case badWord
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        do {
            try checkWord()
        }
        catch SomeError.badWord {
            print("error!")
        }
        catch { //This is like a defualt statement
            print("Something weird happened")
        }

    }

    func checkWord() throws {
        let word = "crap"
        guard word != "crap" else {
            throw SomeError.badWord
        }
        print("Continuing the function")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

如果单词不好,checkWord函数将终止。但是,使用以下方法可以实现相同的行为:

func checkWord() {
  let word = "crap"
  guard word != "crap" else {
    print("error!")
    return

   }
   print("Continuing the function")
 }

那么定义错误和浏览catch语句的用途是什么?

1 个答案:

答案 0 :(得分:2)

对于checkWord的第二次实施,checkWord的来电者无法知道支票的结果。

抛出错误然后捕获它们的整个想法是,你可以清楚地定义处理错误的责任。

例如,您的checkWord函数的工作是检查错误的单词。但它不应该对发现坏词时应该做什么做出任何假设。可以从许多不同的地方调用checkWord,即使是不同的应用程序(例如,如果您在框架中提供它)。所以你的checkWord函数应该检查并在适当时抛出错误。让checkWord的调用者决定如何最好地处理错误。它可能决定向用户显示消息。它可能决定只是记录它并继续前进。关键是,checkWord不应该关心。让来电者决定什么是最好的。