二元运算符%不能应用于UInt32和int类型的操作数

时间:2016-01-28 18:30:33

标签: ios xcode swift

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

我收到错误

  

"二元运算符%不能应用于UInt32类型的操作数   INT&#34 ;.如何修复语法

5 个答案:

答案 0 :(得分:3)

使用以下

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

答案 1 :(得分:1)

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来解决问题。

答案 2 :(得分:1)

语法很好,语义错误。

Swift不喜欢随机类型转换。您收到了非常明确的错误消息:您无法执行UInt32%int。因此,您需要更改其中一个操作数,UInt32%UInt32或int%int(如果这是您的错误消息所说的)。

当然之后,分配将失败,因为您无法将UInt32分配给Int。正如我所说,Swift不喜欢随机类型转换。

答案 3 :(得分:0)

这个也有效:

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

答案 4 :(得分:0)

您应该使用现代%函数,而不是使用arc4random_uniform操作:

let y = Int(arc4random_uniform(5))
相关问题