Reputation: 1469
I want to write the following in a more elegant way:
let number = "1,2922.3"
if number.contains(",") || number.contains(".") && !(number.contains(".") && number.contains(",")) {
// proceed
}
That is, I want to proceed if the number has "." or ",", but not them both.
There has to be a better way?
I don't want to use an extension, as this is in a single place in my code.
Upvotes: 1
Views: 194
Reputation: 2661
You can use SetAlgebra
:
func validate(_ string: String) -> Bool {
let allowed = Set(",.")
return !allowed.isDisjoint(with: string) && !allowed.isSubset(of: string)
}
validate("1,2922.3") // false
validate("1,29223") // true
validate("12922.3") // true
validate("129223") // false
To explain a bit:
!allowed.isDisjoint(with: string)
because you want to exclude strings that contain neither .
nor ,
.!allowed.isSubset(of: string)
because you want to exclude strings that contain both .
and ,
.Upvotes: 5