【问题标题】:Swift: Adding negative numbersSwift:添加负数
【发布时间】:2022-01-17 22:57:53
【问题描述】:

我遇到了一个添加负数的非常简单的问题,但 Apple 文档并没有真正涵盖这一点。

SwiftUI 代码:

Text(String(-50 + 5))

这会引发错误,Compiling failed: Ambiguous use of operator '-'。但是,Text(String(-50)) 不会抛出任何错误。

我尝试将 -50 转换为 Int 并将其括在括号中。此外,如果我将-50 + 5 分配给一个变量,然后在 Text() 中使用该变量,它就可以正常工作。我怎样才能让它显示-45,是什么导致了错误?

注意:在 macOS Monterey 上使用 XCode 13.2.1

编辑:人们要求提供屏幕截图,因为似乎并不是每个人都会出现这个问题。这是一个全新项目中的问题。

【问题讨论】:

  • 该代码在 Xcode 13.1 上对我来说编译和运行良好——您使用的是哪个版本?
  • XCode 13.2.1... 再次检查,我仍然得到同样的错误
  • 如果你这样做Text(String(0 - 50 + 5))会发生什么?
  • 但是你必须解释为什么没有人看到这个。展示更多代码,甚至发布一个演示项目。
  • 该代码适用于我,使用 macos 12.2 Beta 和 Xcode 13.2 编译,针对 ios 15 和 macCatalyst 12。

标签: swift xcode swiftui negative-number


【解决方案1】:

查看 Canvas 诊断:

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

并告诉 Xcode 你想使用哪种类型:

例如

Text(String(-Int(50) + 5))

Text(String(-50.0 + 5))

【讨论】:

    【解决方案2】:

    查看错误,可能代码无法将 -50 重新转换为 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
    

    所以我测试了一些这样的例子是可行的。

    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))
    

    【讨论】:

      猜你喜欢
      • 2017-03-07
      • 1970-01-01
      • 2013-10-20
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      相关资源
      最近更新 更多