重复调用函数以在 Swift 操场上产生当前时差

Repeating a call to a function to produce current time difference in Swift playground

在 swift 操场上,为什么此代码不更新。我想让它输出准确的时间(将来会有倒计时)但是我无法获取当前时间来更新,它只是重复了几次相同的时差。

// 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 ,它曾经被赋值。自然在函数returns之后,这个变量不会被删除,因为是在函数外创建的。当您下次调用此函数时,它会使用具有相同值的相同变量。它是一个单一的变量 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")
}