Catch Objective-C exception in Swift

前端 未结 4 1547
日久生厌
日久生厌 2021-02-07 10:56

I am trying to set the value of an @objc object in my Swift code using obj.setValue(value, forKey: key).

It works fine when the object has the

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 11:40

    Swift 5 version with utility error type:

    NS_INLINE NSException * _Nullable ExecuteWithObjCExceptionHandling(void(NS_NOESCAPE^_Nonnull tryBlock)(void)) {
        @try {
            tryBlock();
        }
        @catch (NSException *exception) {
            return exception;
        }
        return nil;
    }
    
    public struct NSExceptionError: Swift.Error {
    
       public let exception: NSException
    
       public init(exception: NSException) {
          self.exception = exception
       }
    }
    
    public struct ObjC {
    
       public static func perform(workItem: () -> Void) throws {
          let exception = ExecuteWithObjCExceptionHandling {
             workItem()
          }
          if let exception = exception {
             throw NSExceptionError(exception: exception)
          }
       }
    }
    
    

提交回复
热议问题