gpt4 book ai didi

swift - 重复调用函数以在 Swift playground 中产生当前时差

转载 作者:可可西里 更新时间:2023-11-01 02:18:09 25 4
gpt4 key购买 nike

在 swift playground 中,为什么这段代码不更新。我试图让它输出准确的时间(将来会有倒计时),但我无法更新当前时间,它只是重复相同的时差几次。

// initialize the date formatter and set the style
let formatter = NSDateFormatter()
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
formatter.dateStyle = NSDateFormatterStyle.ShortStyle

// get the date time String from the date object
let currentDate = formatter.stringFromDate(currentDateTime)

let dateMakerFormatter = NSDateFormatter()
dateMakerFormatter.calendar = userCalendar
dateMakerFormatter.dateFormat = "mm/dd/yy, hh:mm:ss a"
let endTime = dateMakerFormatter.dateFromString("01/08/16, 11:00:00 PM")
let startTime = dateMakerFormatter.dateFromString(currentDate)
let hourMinuteComponents: NSCalendarUnit = [.Month,.Day, .Hour, .Minute, .Second]
let timeDifference = userCalendar.components(
hourMinuteComponents,
fromDate: startTime!,
toDate: endTime!,
options: [])
timeDifference.month
timeDifference.day
timeDifference.hour
timeDifference.minute
timeDifference.second
func printTimeDifference() {
print("\(timeDifference.month) Months, \(timeDifference.day) Days, \(timeDifference.minute) minutes, \(timeDifference.second) seconds")
}

var done = 0
//printTimeDifference()
var counter:Int = 0

while done != 10 {
sleep(1)
printTimeDifference()
done++
}

我可能在其中放置了太多代码,但主要部分是循环。 当我调用 printTimeDifference() 时,它为什么不打印当前与秒的差异,它只打印当前日期(我假设)第一次调用的时间。据我所知,变量与函数一起生死存亡,每次我调用函数时,它都应该重新创建变量,即及时获取实际的当前差异。 我的猜测是这可能与强链接和弱链接有关,但我对 swift 比较陌生,并且在 C 中做了更多工作。感谢任何帮助。

最佳答案

在你的问题中你写:

To the best of my knowledge the variables live and die with the function, and each time I call the function it should be recreating the variables

这是真的,但前提是变量是在函数内创建的。在您的情况下,您没有在函数 printTimeDifference 中创建新变量,而是使用已经创建的 timeDifference ,它曾经被分配了一个值。函数返回后自然不会删除这个变量,因为它是在函数外创建的。当您下次调用此函数时,它会使用具有相同值的相同变量。它是一个单一变量 timeDifference

如果将所有必要变量的创建转移到函数 printTimeDifference 中,您将获得预期的效果,例如:

func printTimeDifference() {
// Here your code with all variables creation
...
// with this variable you need to print
let timeDifference = userCalendar.components(
hourMinuteComponents,
fromDate: startTime!,
toDate: endTime!,
options: [])
print("\(timeDifference.month) Months, \(timeDifference.day) Days, \(timeDifference.minute) minutes, \(timeDifference.second) seconds")
}

关于swift - 重复调用函数以在 Swift playground 中产生当前时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34605135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com