-1

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

user2206906
  • 1,310
  • 2
  • 13
  • 18
  • 1
    You dont! A Crash is something entirely different to an exception you `throw`. A crash you cannot and must not catch - a crash always indicates a bug that you as the developer introduced. It is your job for example to make sure the ranges are correct. – luk2302 Dec 01 '16 at 09:59
  • yea lol of course, 1st i'm not the best dev ever,2nd i'm not responsible of the data and i do not trust them 3thd i would like to understand. In Objc i could use a try catch, is it not possible in swift ? – user2206906 Dec 01 '16 at 10:00
  • You can't, compare http://stackoverflow.com/questions/38737880/uncaught-error-exception-handling-in-swift. – Martin R Dec 01 '16 at 10:01
  • There is no difference between objc and swift in this regard. Both will and should crash if *you* mess up the ranges. The only difference is that the swift compiler informs you there is no exception, in objc you write a try-catch around it which will simply not have any effect. – luk2302 Dec 01 '16 at 10:02
  • lol, thank you man i understand now, but in Objc i could catch the error :) – user2206906 Dec 01 '16 at 10:03
  • No you cannot catch it in objc either – luk2302 Dec 01 '16 at 10:04

1 Answers1

1

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 */ }
beeb
  • 1,187
  • 11
  • 32
  • You're very welcome. If your question was answered, don't forget to mark the answer as accepted! Cheers – beeb Dec 02 '16 at 09:56