Search code examples
iosswiftguard

Error handling on native methods swift


new to swift i do not understand how to handle error. I have understood, using guard, throw, do and try for my own methods.

But how can i handle errors from apple native methods like :

self.displayContent?.addAttribute(NSFontAttributeName, value: UIFont.fontMainFeedContentFont(), range: NSRange.init(location: 0, length: self.displayContent!.length))

because this can crash, let's say the range is not good, i know it will crash but when i surround this code with a do try catch Xcode tells me that no calls to throwing functions occur within 'try' expression. What i understand is that addAttribute does not handle throws error.

My question is how can i handle the crash of this method ?

Thanks


Solution

  • This method doesn't throw, so you can't catch the error. It seems the only way to be sure the function call will not fail is to manually check that the range is valid.

    You could for example get the range from the string itself with something like rangeOfString(:)

    (attributedString.string as NSString).rangeOfString("foo")
    

    Or simply validate your NSRange bounds against the string.

    if (range.location != NSNotFound && range.location + range.length <= attributedString.length) { /* ok */ }