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.
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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