Catch “IndexOutOfBoundsException” in Swift 2

前端 未结 2 1656
一个人的身影
一个人的身影 2020-12-19 19:21

I got this code in my Playground:

func throwsError() throws{
    var x = [1,2]
    print(x[3])
}

func start(){

    do{
        try throwsError()

    }
            


        
相关标签:
2条回答
  • 2020-12-19 20:14

    In Swift, you can't catch anything. You can only catch errors thrown with the throw statement in other Swift code or errors, of type NSError set by called Objective C code.

    The default array subscript raises an exception, but does not throw a Swift error, so you cannot use try/catch with it.

    See also this article by Erica Sadun.

    0 讨论(0)
  • 2020-12-19 20:15

    You can write your own method. Not really elegant, but works.

    enum ArrayError: ErrorType {
        case OutOfBounds(min: Int, max: Int)
    }
    
    extension Array {
    
        mutating func safeAssign(index:Int, value: Element) throws {
    
            guard self.count > index && index >= 0 else {
                throw ArrayError.OutOfBounds(min: 0, max: (self.count - 1))
            }
    
            self[index] = value
    
        }
    }
    
    var myArray : [Float] = [1,2]
    
    do {
        try myArray.safeAssign(1, value: Float(5))
    } catch ArrayError.OutOfBounds(let min, let max) {
        print("out of bounds : \(min) => \(max)")
    }
    
    0 讨论(0)
提交回复
热议问题