二元运算符“+”不能应用于“DispatchTime”和“Int32”类型的操作数

Mat*_*w N 5 swift4

我正在尝试为 Swift4 中的计时器设置可变时间延迟,但是当我输入变量时,出现错误:

Binary operator '+' cannot be applied to operands of type 'DispatchTime' and 'Int32'
Run Code Online (Sandbox Code Playgroud)

我使用了代码:

let when = (DispatchTime.now() + (5 * x))
Run Code Online (Sandbox Code Playgroud)

变量“x”是一个 Int32

如果您知道如何修复它,请帮助。

kub*_*lay 25

var dispatchAfter = DispatchTimeInterval.seconds(1)

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + dispatchAfter, execute: {
    // Do your thing
})
Run Code Online (Sandbox Code Playgroud)


Alb*_*ops 5

你可以这样做:

let x: Int32 = 2
let when = (DispatchTime.now().uptimeNanoseconds + (5 * UInt64(x)))
Run Code Online (Sandbox Code Playgroud)

问题是你不能对不同类型求和。DispatchTime 使用 64 位(无符号)表示,因此您可以使用UInt64(x).

要从 DispatchTime 获取,UInt64您可以使用uptimeNanosecondsrawValue