NSAttributedString gets attributes outside of exception

I am trying to get attributes from an attribute string. Everything is fine if the line is not 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 am I getting an out of bounds exception on the last line?

+3


source to share


2 answers


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

Due to indexing starting at 0, index = 0 only exists for String.length> 0.



You can check this easily by using a string of length 1 and entering 1 in 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

      

+3


source


Since you don't care about longestEffectiveRange, use whichever is attribute(_:at:effectiveRange:)

more efficient.

Both will throw if you call an empty string. This is because the parameter at location:

must be within the string. The docs for it says:



Attention!

Raises the exclusion of the range if the index is outside of the destination symbols.

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

+1


source







All Articles