Swift: Adding negative numbers
I've got a pretty simple problem with adding negative numbers, but Apple Documentation doesn't really cover this.
SwiftUI Code:
Text(String(-50 + 5))
This throws the error, Compiling failed: Ambiguous use of operator '-'
. However, Text(String(-50))
doesn't throw any errors.
I've tried casting -50 as an Int and wrapping it in parentheses. Also, if I assign -50 + 5
to a variable, and then use the variable in the Text(), it works fine. How can I get this to display -45, and what's causing the error?
Note: Using XCode 13.2.1 on macOS Monterey
EDIT: People are asking for a screenshot, as it seems the issue isn't occurring for everyone. Here's the issue in a brand new project.
Solution 1:
Check out Canvas diagnostics:
Swift.Float16:3:31: note: found this candidate
prefix public static func - (x: Float16) -> Float16
^
Swift.Float:2:31: note: found this candidate
prefix public static func - (x: Float) -> Float
^
Swift.Double:2:31: note: found this candidate
prefix public static func - (x: Double) -> Double
^
Swift.Float80:2:31: note: found this candidate
prefix public static func - (x: Float80) -> Float80
and tell Xcode which type you wanna use:
e.g.
Text(String(-Int(50) + 5))
or
Text(String(-50.0 + 5))
Solution 2:
See the error, it probably code can't reconize -50 to int.
Swift.Float16:3:31: note: found this candidate
prefix public static func - (x: Float16) -> Float16
^
Swift.Float:2:31: note: found this candidate
prefix public static func - (x: Float) -> Float
^
Swift.Double:2:31: note: found this candidate
prefix public static func - (x: Double) -> Double
^
Swift.Float80:2:31: note: found this candidate
prefix public static func - (x: Float80) -> Float80
So I test for some example like this is wrok.
let a = -Int(50) + 3
let b = -50.0 + 3
let c:Int = -50 + 3
Text(String(-Int(50) + 3))
Text(String(a))
Text(String(b))
Text(String(c))