简体   繁体   中英

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")
}

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.

To remove warning just remove try { } . removeObserver:forKeyPath: is throwing an exception and not an error. And you cannot catch exceptions in Swift so make sure you call this method only if you observing it otherwise it will crash and there is no way around it in Swift.

You could write a category in Objective-C that wraps this call and capture the exception and returns an error instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM