Search code examples
swiftnsattributedstring

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?


Solution

  • 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