Kubba
Kubba

Reputation: 3438

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?

Upvotes: 6

Views: 2711

Answers (2)

David Pasztor
David Pasztor

Reputation: 54706

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

Upvotes: 5

Lou Franco
Lou Franco

Reputation: 89142

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

Upvotes: 2

Related Questions