看看这段代码:
var timepenalty = UInt8(0)
var currentTime = NSDate.timeIntervalSinceReferenceDate()
// Find the difference between current time and start time
var elapsedTime: NSTimeInterval = currentTime - startTime
let adjustedTime = UInt8(timepenalty + elapsedTime)
error-
"Could not find an overload for "+" that accepts the requested arguments.
"这是一个游戏,为秒表式计时器增加时间,每次玩家犯错。当我只使用一个整数而不是elapsedTime变量时,代码就会工作,如下所示:
let adjustedTime = UInt8(elapsedTime + 5) 但是用变量替换5会产生一个错误。
下面是updateTime函数的完整代码:
func updateTime() {
var currentTime = NSDate.timeIntervalSinceReferenceDate()
// Find the difference between current time and start time
var elapsedTime: NSTimeInterval = currentTime - startTime
let adjustedTime = UInt8(timepenalty + elapsedTime)
// calculate the minutes in elapsed time
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
// calculate the seconds in elapsed time
seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
// seconds += timepenalty
// find out the fraction of millisends to be displayed
let fraction = UInt8(elapsedTime * 100)
// if seconds > 20 {
// exceedMsgLabel.text = "超过20秒了"
// }
// add the leading zero for minutes, seconds and millseconds and store them as string constants
let startMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
let startSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
let startFraction = fraction > 9 ? String(fraction):"0" + String(fraction)
displayTimeLabel.text = "\(startMinutes):\(startSeconds):\(startFraction)"
var penalty = String(timepenalty)
penaltylabel.text = "+ " + penalty
}发布于 2015-02-19 14:09:58
这一行:
let adjustedTime = UInt8(timepenalty + elapsedTime)试图添加UInt8 (时间限制)和NSTimeInterval (double,elapsedTime),由于Swift中没有隐式类型转换而失败。改为:
let adjustedTime = timepenalty + UInt8(elapsedTime)它在添加之前将NSTimeInterval转换为UInt8。
发布于 2015-02-19 14:21:24
@David的代码很好,但我强烈建议您让adjustedTime成为一个NSTimeInterval。这是一个时间间隔,这就是类型的目的。那你的选角问题就都解决了。
UInt8类型保留在您显式需要8位位模式(如网络协议或二进制文件格式)的情况下。它不是为“小数字”设计的。在有符号和无符号的数字和不同大小的数字之间移动是常见的bug来源,并且有意使其变得很麻烦。
如果您确实需要强制Double成为一个整数,那么在大多数情况下只需要使用Int而不是UInt8。在大多数情况下,看起来您实际上是指floor()而不是Int()。你只是在正常地处理整个数字。
尽管如此,一种更典型的格式化方法是:
import Foundation
let totalSeconds: NSTimeInterval = 100.51
let frac = Int((totalSeconds - floor(totalSeconds)) * 100)
let seconds = Int(totalSeconds % 60)
let minutes = Int((totalSeconds / 60) % 60)
let result = String(format: "%02d:%02d:%02d", minutes, seconds, frac)发布于 2015-02-19 13:36:55
UInt8和NSTimeInterval是两种不同的类型。您需要使每个操作数都具有相同的类型。(或者可以使用操作符重载。)
https://stackoverflow.com/questions/28607700
复制相似问题