【发布时间】:2021-10-19 11:37:40
【问题描述】:
我有一个小问题,我对 Swift 太缺乏经验,无法自己解决。如果有人做过类似的事情或对我有一些建议,我将不胜感激。 所以这是我的问题。我有一个应用程序正在选择的文本文件。文件本身由时间戳和一行代码组成。我将两者分开并将它们保存在数组中。时间戳的间隔不均匀,但我需要在相应的时间发送代码行。
extension String {
var integer: Int {
return Int(self) ?? 0
}
// Converting the String Timestamp to a Float Value
var secondsfromString: Float {
var components : Array = self.components(seperatedBy: ":")
let minutes = components[0].integer
let seconds = components[1].integer
let milliseconds = components[2].integer / 100
return Float((minutes * 60) + seconds + milliseconds)
}
}
if let path = Bundle.main.path(forResource: "", ofType: "cs2") {
do {
// Getting file content and removing empty lines
let contents = try String(contentsofFile: path)
let newlines = contents.split(whereSeperator: \.isNewline)
// counting the Array
let x = newlines.count as Int
// Preallocating the Arrays and seperating timestamp and code
var timestamp = [Sting]{repeating: "", count: x}
var codelines = [Sting]{repeating: "", count: x}
for counter in 0...x-1 {
timestamp[counter] = "" + newlines[counter].prefix(8)
codelines[counter] = "" + newlines[counter].suffix(26)
}
// Getting the time in seconds from timestamp
var time = [Float](repeating: 0, count: x)
for counter in 0...x-1 {
time[counter] = 0 + timestamp[counter].secondsfromString
}
// Getting the interval between each Timestamp
var y = [Float](repeating: 0, count: x)
y[0] = time[0]
for i in 0...x-2 {
y[i+1] = time[i+1] - time[i]
}
// Here I want to send Data with the intervals I got from
// the Text file
var timer = [Timer]()
for t in 0...x-1 {
timer[t] = Timer.scheduledTimer(
.withTimeInterval: TimeInterval(y[t]),
.repeats: false, block: { timer in
//code to send Data, not yet done
})
}
我已经用 Timers 尝试了一些事情,例如,当我使用没有循环的计时器时,我设法让第一个计时正确,但所有其他的时间间隔都与第一个相同,这不是文本文件给了我。当我将计时器放入没有数组计时器的循环中时,它会“立即”执行所有操作,甚至第一个间隔都不正确。现在我想尝试制作一组计时器来完成它,但我就是无法让它工作。在这种情况下使用计时器是否正确,或者有更好的方法吗?
【问题讨论】: