【问题标题】:Using variable as lower bound for arc4random - explicit type/strideable?使用变量作为 arc4random 的下限 - 显式类型/可跨步?
【发布时间】:2023-12-20 20:35:02
【问题描述】:

)

我更新了一个“锻炼对象”,使其具有最小和最大重复次数。

当我在操场上硬编码下限时,我一直在使用:

let numberOfExercises = Int(arc4random_uniform(4) + 3)

当我尝试在函数中/与类对象一起使用变量时,我收到“+'不可用:请使用显式类型转换或混合类型算术的 Strideable 方法”的错误,例如这里...

class ExerciseGeneratorObject: Object {
    @objc dynamic var name = ""
    @objc dynamic var minReps = 0
    @objc dynamic var maxReps = 0    

    convenience init(name: String, minReps: Int, maxReps: Int) {
        self.init()
        self.name = name
        self.minReps = minReps
        self.maxReps = maxReps
    }

    func generateExercise() -> WorkoutExercise {
        return WorkoutExercise(
            name: name,
//get error on this line...
            reps: Int(arc4random_uniform(UInt32(maxReps))+minReps)
        )
    }
}

+ is unavailable: Please use explicit type conversions or Strideable methods for mixed-type arithmetics 这里有一个答案,但该方法已经在使用,所以看不到它在这里如何适用。

也在这里'+' is deprecated: Mixed-type addition is deprecated in Swift 3.1 但再次认为这是一个不同的问题

【问题讨论】:

  • 使用这个Int(arc4random_uniform(UInt32(maxReps)))+minReps

标签: ios swift4 swift4.1


【解决方案1】:

“+”不可用:请对混合类型算术使用显式类型转换或 Strideable 方法。

例子:

let a: UInt32 = 4
let b = 3

let result = a + b //error

基本上意味着您不能添加混合类型


在您执行arc4random_uniform(UInt32(maxReps)) + minReps 的情况下,arc4random_uniform() 返回一个UInt32,它不能添加到minReps,因为这是一个Int

解决办法:

更新括号:

let numberOfExercises = Int(arc4random_uniform(UInt32(maxReps))) + minReps

这里Int(arc4random_uniform(UInt32(maxReps))) 给出了一个Int,我们可以将它添加到minReps Int


顺便说一句,以下工作开箱即用:

let numberOfExercises = Int(arc4random_uniform(4) + 3)

因为 Swift 的自动类型推断。基本上它只是继续使用UInt32 而不会打扰你。那就是......直到你给它明确的混合类型。

【讨论】:

  • 这行得通 - 起初它没有但意识到我叫错了!
  • @nc14 很高兴知道!快乐编码:)
最近更新 更多