如果你在 Swift 中设计一个函数(或方法),你至少有 3 种选择来处理错误:
选择 1:返回可选类型
如果您的函数可能会失败,并且这种情况经常发生,那么请考虑返回一个可选类型变量。例如,在您的情况下,您的方法 add 可能会返回 NSDecimalNumber? 而不是普通的 NSDecimalNumber。在这种情况下,您的方法将检查所有可能出错的内容,并在这些情况下返回 nil。上溢和下溢将返回nil,所有其他情况将返回NSDecimalNumber。调用者必须像这样检查并打开可选的 NSDecimalNumber:
let brain = MathWhiz()
if let sum = brain.add("1", op2: "1e127") {
println("the result was \(sum)")
} else
println("something went wrong with MathWhiz add")
}
选择 2:返回枚举类型
如果您想返回有关出错的更多信息,您可以创建一个枚举类型,其中每个错误都有一个值,而成功则嵌入答案。例如,您可以这样做:
enum MathWhizResult {
case Overflow
case Underflow
case Success(NSDecimalNumber)
}
然后 add 将被定义为返回 MathWhizResult:
func add(op1: String, op2: String) -> MathWhizResult
如果出现错误,add 将返回 .Overflow 或 .Underflow。在成功的情况下,add 将返回 Success(result)。调用者必须检查枚举并解包结果。 switch 可用于此:
switch (brain.add("1", op2: "1e128")) {
case .Overflow
println("darn, it overflowed")
case .Underflow
println("underflow condition happened")
case .Success(let answer)
println("the result was \(answer)"
}
选择 3:选择不明确处理错误
解包前两个选项中的结果可能会导致非常罕见的错误的开销太大。您可以选择只返回一个结果,让调用者处理下溢或溢出情况的可能性。在这种情况下,他们必须在致电add 之前自己检查这些情况。好处是,如果他们知道他们的程序永远不会导致下溢或溢出(例如,因为他们正在处理一位数),他们就不会为解压结果而烦恼。
我创建了一个小应用程序来演示如何使用NSDecimalNumbers 完成此操作。我在Xcode 中创建了一个Single View Application。在ViewController 和StoryBoard 中,我添加了3 个TextFields(操作数1、操作数2 和结果各一个)和一个我标记为+ 的Button。
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet var operand1 : UITextField!
@IBOutlet var operand2 : UITextField!
@IBOutlet var result : UITextField!
var brain = MathWhiz()
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 addButton(sender : UIButton) {
var op1 = operand1.text
var op2 = operand2.text
// Perform the add with the contents of the operand fields.
// Print the answer, or "No Result" if add returns nil.
if let answer = brain.add(op1, op2: op2)?.description {
result.text = answer
} else {
result.text = "No Result"
}
}
}
MathWhiz.swift
import UIKit
// Declare that we implement NSDecimalNumberBehaviors so that we can handle
// exceptions without them being raised.
class MathWhiz: NSDecimalNumberBehaviors {
var badException = false
// Required function of NSDecimalNumberBehaviors protocol
func roundingMode() -> NSRoundingMode {
return .RoundPlain
}
// Required function of NSDecimalNumberBehaviors protocol
func scale() -> CShort {
return CShort(NSDecimalNoScale)
}
// Required function of NSDecimalNumberBehaviors protocol
// Here we process the exceptions
func exceptionDuringOperation(operation: Selector, error: NSCalculationError, leftOperand: NSDecimalNumber, rightOperand: NSDecimalNumber) -> NSDecimalNumber? {
var errorstr = ""
switch(error) {
case .NoError:
errorstr = "NoError"
case .LossOfPrecision:
errorstr = "LossOfPrecision"
case .Underflow:
errorstr = "Underflow"
badException = true
case .Overflow:
errorstr = "Overflow"
badException = true
case .DivideByZero:
errorstr = "DivideByZero"
badException = true
}
println("Exception called for operation \(operation) -> \(errorstr)")
return nil
}
// Add two numbers represented by the strings op1 and op2. Return nil
// if a bad exception occurs.
func add(op1: String, op2: String) -> NSDecimalNumber? {
let dn1 = NSDecimalNumber(string: op1)
let dn2 = NSDecimalNumber(string: op2)
// Init badException to false. It will be set to true if an
// overflow, underflow, or divide by zero exception occur.
badException = false
// Add the NSDecimalNumbers, passing ourselves as the implementor
// of the NSDecimalNumbersBehaviors protocol.
let dn3 = dn1.decimalNumberByAdding(dn2, withBehavior: self)
// Return nil if a bad exception happened, otherwise return the result
// of the add.
return badException ? nil : dn3
}
}