'Swift || do we possible to detect how many spaces of empty string have?

lets say we have an extension of String:

extension String {
  var textBeCleared: Bool {
   // how we write here
  }
}

then:

var demo1 = ""  // no space over here
demo.textBeCleared // true
var demo2 = " " // type one space over here
demo.textBeCleared // false

because I got a sticky issue is: I have a save button at bottom of a text field, save button only displays when removing all text contents in the text field, like demo1. but if type more space over here, like demo2, save button will be hidden.



Solution 1:[1]

you could try this:

extension String {
  var textBeCleared: Bool {
      self.isEmpty
  }
}

var demo1 = ""  // no space over here
var demo2 = " " // type one space over here
print(" demo1.textBeCleared: \(demo1.textBeCleared) ") // true
print(" demo2.textBeCleared: \(demo2.textBeCleared) ") // false

Solution 2:[2]

User filter for this purpose. It will filter each char in the string and you will get your expected result.

let inputString1 = "   "
let inputString2 = ""
let inputString3 = "a"
let spacesCount1 = inputString1.filter { $0 == " " }
print(spacesCount1.count)
let spacesCount2 = inputString2.filter { $0 == " " }
print(spacesCount2.count)
let spacesCount3 = inputString3.filter { $0 == " " }
print(spacesCount3.count)

Output

3
0
0

Solution 3:[3]

thanks guys, I managed solved this by following code

let inputString1 = "   "
let inputString2 = ""
let inputString3 = "a"


extension String {
    var textBeCleared: Bool {
        !self.contains(" ") && allSatisfy { $0.isWhitespace }
    }
}
inputString1.textBeCleared // false
inputString2.textBeCleared // true
inputString3.textBeCleared // false

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 workingdog support Ukraine
Solution 2 Ashis Laha
Solution 3 zitherC