I have a string that contains a number. I want to add a minus sign if it’s not there or remove it if it is there. I have a working function, but I’m wondering if there’s a better way.
private func toggleAmountSign()
{
if amount.first == "-"
{ amount.removeFirst() }
else
{ amount.insert("-", at: amount.startIndex) }
}
This forum always teaches me something, so I figure maybe I can get another lesson.
Seems to be alright, but I would also look for 0, not just for a “-” before the number.
In your code, you would get a -0, which is strange.
You may want to check if your number is negativ or positiv by using signum(), instead of looking for a “-” (user may also write “—” or space -)
You don’t even need to use signum
at all. Just multiply your number by -1
and that will flip whatever the sign is to the opposite.
extension String {
var toggledSign: String {
return String((Int(self) ?? 0) * -1)
}
}
let test = [
"1",
"3",
"-13",
"0",
"27",
"-27",
"george"
]
print(test.map(\.toggledSign))
//["-1", "-3", "13", "0", "-27", "27", "0"]
Note that for simplicity, I just had anything that can’t be converted to an Int
become 0
, but you could handle that situation a number of different ways. For instance:
extension String {
var toggledSign: String {
guard let num = Int(self) else {
return self
}
return String(num * -1)
}
}
And you could include other kinds of bulletproofing, like trimming the string before converting it just in case there are extraneous spaces, etc.
Thanks for the suggestions. I do check for validity with
if Double(amount) == nil
Good ideas. Once again, I learned something from this forum.