Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString get attributes out of bounds exception

I'm trying to get attributes from attributed string. Everything is ok unless string is empty. Take a look:

let s = NSAttributedString(string: "", attributes: [NSForegroundColorAttributeName: UIColor.red])
let range = NSMakeRange(0, s.length)
let attrs = s.attributes(at: 0, longestEffectiveRange: nil, in: range)

Why I'm getting Out of bounds exception on last line?

like image 352
Kubba Avatar asked May 26 '17 13:05

Kubba


2 Answers

This is the expected result. If a string's length is 0 (the case for ""), it has no character at index 0, so when you are trying to access it with s.attributes, you are expected to get an out of bounds exception.

Because of the fact that indexing start from 0, index=0 only exists for String.length>0.

You can easily check this by using a string of length 1 and inputting 1 to s.attributes.

let s = NSAttributedString(string: "a", attributes: [NSForegroundColorAttributeName: UIColor.red])
let range = NSMakeRange(0, s.length)
let attrs = s.attributes(at: 1, longestEffectiveRange: nil, in: range)    //also produces out of bounds error
like image 169
Dávid Pásztor Avatar answered Sep 23 '22 02:09

Dávid Pásztor


Since you don't care about the longestEffectiveRange, use attribute(_:at:effectiveRange:) which is more efficient.

Both will throw if you call on an empty string. This is because the at location: parameter must be within the bounds of the string. The docs for it say:

Important

Raises an rangeException if index lies beyond the end of the receiver’s characters.

https://developer.apple.com/reference/foundation/nsattributedstring/1408174-attribute

like image 33
Lou Franco Avatar answered Sep 24 '22 02:09

Lou Franco