【问题标题】:How to stop crashing in swift3 using try catch如何使用 try catch 停止在 swift3 中崩溃
【发布时间】:2017-07-15 09:33:53
【问题描述】:

在目标 c 中,我们使用 try catch 来停止崩溃,例如

- (void)viewDidLoad {
[super viewDidLoad];

tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];



@try {
    NSLog(@"%@",tableData[1000]);
     } @catch (NSException *exception) {
    NSLog(@"%@",exception);
  }  
 }

但是当我使用 swift 3 时,警告显示和应用程序崩溃

谁能解释一下,我该如何阻止它。我从谷歌阅读了一些主题,但无法理解。谁能帮帮我。

【问题讨论】:

标签: swift


【解决方案1】:

Swift 数组实现了一个下标,以便于访问其成员。下标不能抛出。您可以实现对 Collection 协议的扩展,并创建一个抛出函数,如果索引低于 Colllection 的 (.count-1),则获取成员,如果高于则抛出错误。

或者,您可以实现一个返回常量的下标,然后防范该常量,并在守卫的 else 语句中抛出错误(但除非您在该 do 块中有 try 语句,否则它将是有点语法上的脂肪)。

【讨论】:

    【解决方案2】:

    您可以通过简单的步骤实现它,请查看:

    // define your array
    let array : [String] = ["One","Two"]
    
    // define your array error
    enum ArrayError : Error {
            case OutOfBoundsError(String)
    }
    
    // this method will return if its a valid or invalid value for array index.
    private func getValueForIndex(index:Int)->String?{
    
        if array.count > index && index >= 0{
            return array[index]
        }else {
            return nil
        }
    
    }
    

    您可以使用 guard let 将错误抛出到 catch 块中,使用 try 和 catch 轻松处理它,如下所示:

        do {
    
            guard let index1 = try getValueForIndex(index: 0) else { throw ArrayError.OutOfBoundsError("Out of bounds for \(0)") }
            guard let index2 = try getValueForIndex(index: 1) else { throw ArrayError.OutOfBoundsError("Out of bounds for \(1)") }
            guard let index3 = try getValueForIndex(index: 2) else { throw ArrayError.OutOfBoundsError("Out of bounds for \(2)") }
            guard let index4 = try getValueForIndex(index: 3) else { throw ArrayError.OutOfBoundsError("Out of bounds for \(3)") }
    
        } catch{
    
            print(error)
    
        }
    

    这是解决方法,还有很多其他方法,并且可能会因为我保持简单而变得复杂。请让我知道这对你有没有用 !

    【讨论】:

    • 这个答案非常违反直觉。 getValueForIndex() 函数应该用 throws 标记,并且应该从 else 中抛出,而不是在 do 中手动抛出。
    • 他需要尝试捕获一个函数,而不是返回的函数吗?
    猜你喜欢
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多