【问题标题】:binary operator % cannot be applied to operands of type UInt32 and int二元运算符 % 不能应用于 UInt32 和 int 类型的操作数
【发布时间】:2016-01-28 18:30:32
【问题描述】:
var Y: Int = 0
Y = arc4random() % 5

我收到了错误

"二元运算符 % 不能应用于 UInt32 类型的操作数和 int"。如何修复我的语法

【问题讨论】:

    标签: ios xcode swift


    【解决方案1】:

    使用以下

    var Y: Int = 0
    Y = Int( arc4random() % 5 )
    

    【讨论】:

    • 无法编译。
    • 对我有用。刚刚在操场上验证
    • @Brduca 它对我来说很好,但没有编译,因为我正在处理其他错误,所以我无法编译。
    • 我会回复你们的
    • 在 ball.center = CGPointMake(ball.center.x + X, ball.center.y + Y) “二元运算符 + 不能应用于 CGfloat int 类型的操作数”上遇到同样的问题。我尝试用相同的方法修复它,但没有奏效
    【解决方案2】:
    import Foundation
    
    var Y: UInt32 = 0
    Y = arc4random() % 5
    

    % 函数返回一个 UInt32。

    来自 Apple 文档:

    /// Divide `lhs` and `rhs`, returning the remainder and trapping in case of
    /// arithmetic overflow (except in -Ounchecked builds).
    @warn_unused_result
    public func %<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T
    
    public func %(lhs: Int64, rhs: Int64) -> Int64
    
    public func %(lhs: Int8, rhs: Int8) -> Int8
    
    public func %(lhs: UInt64, rhs: UInt64) -> UInt64
    
    public func %(lhs: Int32, rhs: Int32) -> Int32
    
    public func %(lhs: UInt32, rhs: UInt32) -> UInt32
    
    public func %(lhs: Int16, rhs: Int16) -> Int16
    
    public func %(lhs: UInt16, rhs: UInt16) -> UInt16
    
    public func %(lhs: UInt8, rhs: UInt8) -> UInt8
    
    public func %=(inout lhs: Float, rhs: Float)
    
    public func %=(inout lhs: Double, rhs: Double)
    
    public func %=(inout lhs: Float80, rhs: Float80)
    

    这是 % 的重载,因为唯一允许 UInt32 作为第一个参数的方法,响应类型是 UInt32。 您可以通过将结果转换为 Int 或将 var Y 更改为 UInt32 来解决问题。

    【讨论】:

    • 它与 % 无关:发生的情况是 arc4random 返回 UInt32,但 Swift 擅长推断类型,因此它决定在这种情况下 5也是一个 UInt32 而不仅仅是一个 Int,所以类型“神奇地”匹配。
    • @EricD。遵循苹果文档“public func %(lhs: UInt32, rhs: UInt32) -> UInt32”。在这种情况下,% 的返回类型是 UInt32。
    • 这是一个重载的运算符,它在这里使用 UInt32 因为这是推断的类型,正如我解释的那样。尝试将 % 与两个 Ints 一起使用,您就会明白会发生什么......
    • 是的,当我说它不能以两种方式编译时我错了。
    【解决方案3】:

    语法很好,语义错误。

    Swift 不喜欢随机类型转换。你有一个非常明确的错误信息:你不能做 UInt32 % int。因此,您需要更改其中一个操作数,即 UInt32 % UInt32 或 int % int (如果这是您的错误消息所说的话)。

    当然之后赋值会失败,因为你不能将 UInt32 赋值给 Int。正如我所说,Swift 不喜欢随机类型转换。

    【讨论】:

      【解决方案4】:

      这个也可以:

      var Y: Int = 0
      Y = Int(arc4random() % UInt32(5))
      

      【讨论】:

        【解决方案5】:

        与其使用% 操作,不如使用现代的arc4random_uniform 函数:

        let y = Int(arc4random_uniform(5))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-02
          • 2016-09-20
          • 2015-08-12
          • 2015-10-22
          • 2015-10-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多