Dan A
Dan A

Reputation: 209

binary operator % cannot be applied to operands of type UInt32 and int

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

I am getting the error

"binary operator % cannot be applied to operands of type UInt32 and int". How can I fix my syntax

Upvotes: 5

Views: 5411

Answers (5)

Sulthan
Sulthan

Reputation: 130132

Instead of using the % operation, you should rather use the modern arc4random_uniform function:

let y = Int(arc4random_uniform(5))

Upvotes: 0

Daewizal Forshizal
Daewizal Forshizal

Reputation: 141

This one also works:

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

Upvotes: 1

gnasher729
gnasher729

Reputation: 52602

The syntax is fine, the semantics is wrong.

Swift doesn't like random type conversions. You've got a very clear error message: You can't do UInt32 % int. So you need to change one of the operands, either UInt32 % UInt32 or int % int (if that's what your error message said).

Of course after that the assignment will fail, because you can't assign UInt32 to Int. As I said, Swift doesn't like random type conversions.

Upvotes: 1

brduca
brduca

Reputation: 3623

import Foundation

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

The % function returns an UInt32.

From Apple docs:

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

this are the overloads of %, since the only method that allows an UInt32 as first parameter the response type is an UInt32. You can solve the problem by casting the result to an Int or changing the var Y to UInt32.

Upvotes: 1

Vishnu gondlekar
Vishnu gondlekar

Reputation: 3956

Use following

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

Upvotes: 3

Related Questions