Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2 : Try/Catch a non-throwing function

I'm refactoring a Obj-c class where there was a @try/@catch block around removeObserver:.

Doing the same thing in swift triggers a warning since removeObserver might fail (when there is no observer) but it doesn't throw any errors.

Any idea how I could achieve the same behaviour ?

edit : My code :

try {  
    self.removeObserver(self, forKeyPath: "LineDisplayChanged")
}
like image 780
Matthieu Riegler Avatar asked Aug 26 '15 19:08

Matthieu Riegler


1 Answers

The func removeObserver(_ anObserver: NSObject,forKeyPath keyPath: String) you are calling is from the NSKeyValueObserving protocol and does not throws any exceptions.

Also, note that in Swift 2 the syntax for exception(that are actually ErrorType enum subclasses) has changed and is now something like this:

do{
   try functionThrowingExceptions()

}catch ErrorTypeSubclassEnum.Value {
   // Do something
}catch ErrorType {
   // Do something, catches everything else
}

See this post for more info.

Note: I'm using KVO with the latest beta of XCode7, doing a self.removeObserver(self, forKeyPath: "path") does not trigger any error/warning.

like image 143
uraimo Avatar answered Sep 22 '22 04:09

uraimo