0

I'm trying to find the number of strings that have a url attribute in an attribute string. For example, I'd have something like this: @"Hello there my name is Michael".

name is a string with a url property like this {URL: "www.google.com"}.

I want to find the number of strings with urls in my attributed string. I tried to use enumerateAttributes over my string but this only returned attributes that apply to the whole string. When I print out my string I can clearly see that there are strings with this attribute. How can I access them?

1 Answer 1

1

You’re close. For this you can use the enumerateAttribute(_:in:options:using:) method. You pass in the attribute you are interested in (in your case .link) and it calls the closure with each subrange of the string with the range and the value of the attribute. This includes subranges that don’t have that attribute. In this case nil is passed for the value. So to count the links in your string you count the non-nil attributes:

func linksIn(_ attributedString: NSAttributedString) -> Int {
  var count = 0
  attributedString.enumerateAttribute(.link, in: NSRange(location: 0, length: attributedString.length), options: []) { attribute, _, _ in
    if attribute != nil {
        count += 1
    }
  }
  return count
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah yeah I figured it out by myself but this is the correct answer I used

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.