我发现使用let来验证变量是零还是以前设置过值非常混乱。

var birthDate: NSDate?

有一个表单,用户可以在其中设置生日,并为该变量分配一个值。
稍后在dosave方法中,我想验证此字段是否已填充
@IBAction func doSave(sender: AnyObject) {
...
if birthDate == nil {
    doAlert("You need to specify your birth date")
} else { ... continue save ... }

我获得的最佳方法是根据another related question创建第二个变量。
if let bd = birthDate! as? NSDate { ... continue save ... }
else { doAlert("You need to specify your birth date") }

我只收到警告:从“nsdate”到“nsdate”的条件强制转换始终成功
这是实现这一目标的唯一途径吗?有没有什么不那么凌乱的?

最佳答案

var birthDate: NSDate?

if let birthDate = birthDate {
    println(birthDate.descriptionWithLocale(NSLocale.currentLocale())!)
} else {
    println("birthDate is nil")
}

birthDate = NSDate()
if let birthDate = birthDate {
    println(birthDate.descriptionWithLocale(NSLocale.currentLocale())!)
} else {
    println("birthDate is nil")
}

关于swift - 如果NSDate没有让我快速检查是否为零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30687818/

10-12 02:06