could not find an overload for '+' that ac

2020-07-22 16:16发布

So I am trying to convert a game I was making in Objective-C to Swift.

I am trying to get this to work, but it keeps giving me an error.

    var actualX = (Double(arc4random() ) % Double(rangeX) ) + Double(minX);

I have also tried:

    var actualX = (arc4random() % rangeX) + minX;

I have looked at the other posts on Stack Overflow of similar problems, but none of them have helped or solved my problem...

标签: swift
2条回答
做自己的国王
2楼-- · 2020-07-22 16:51

This works fine for me:

import Cocoa

let minX = 3.2
let rangeX = 42.0 

let actualX = (Double(arc4random()) % rangeX) + minX

After execution actualX will be a Double because of type inference of Swift.

@otherRepliants: Of course arc4random() returns an UInt32, but why not cast it to Double. Works fine.

查看更多
够拽才男人
3楼-- · 2020-07-22 16:52

arc4random() returns a UInt32, any argument to your % operator has to be a compatible type.

Co-erce your variables to a UInt32. You don't mention what type they are, but I am assuming they are some form of integer. You can obviously coerce to another type later.

var actualX = (arc4random() % UInt32(rangeX)) + UInt32(minX)

This is a result of the strong typing in swift.

查看更多
登录 后发表回答