swiftstringnsattributedstringnsmutableattributedstring

Swift - check if attributed text is empty


I have a UITextField on which I set a current value as attributed text as follows:

public var currentValue: NSAttributedString {
    get {
        return inputField.attributedText ?? NSAttributedString()
    }
    set {
        inputField.attributedText = newValue
    }
}

This was previously just a String but I now need to add formatting to parts of the text.

However, I have a method I need to pass on these fields which begins with the condition to see if the field is empty. Previously I started this with:

if textField.currentValue.isEmpty {
  // Perform logic
}

However, obviously NSAttributedText has no isEmpty member. How can I perform the same check on NSAttributedText?


Solution

  • NSAttributedText has no isEmpty property but it has one called length. You can simply check if it is equal to zero:

    if currentValue.length == .zero {
      // Perform logic
    } 
    

    Another option is to simply check if your text field hasText

    if textField.hasText {
    
    } else {
    
    }