ios - 为什么我得到 "fatal error: unexpectedly found nil while unwrapping an Optional value"?

标签 ios swift

<分区>

我在 Swift 中收到一个我不理解的错误。这是我的 Playground 上的代码:

class Person : CustomStringConvertible
{

    let Name :String;
    let DoB :NSDate?

    init(name :String, dob :NSDate?)
    {
        Name = name;
        DoB = dob;
    }

    func age() -> Double {
        let now = NSDate();
        let age :Double = now.timeIntervalSinceDate(self.DoB!);

        return age;
    }

    var description : String {
        return "Name: \(Name), Age: \(self.age())";
    }

}

extension NSDate {
    static func dateFromComponents(year :Int, month :Int, day :Int) -> NSDate {
        let components = NSDateComponents();
        components.year = year;
        components.month = month;
        components.day = day;
        return components.date!;
    }
}

let helena = Person(name: "Helena", dob: NSDate.dateFromComponents(1986, month: 8, day: 10));
print(helena);

最佳答案

NSDateComponents date 属性的文档:

Returns nil if the calendar property value of the receiver is nil or cannot convert the receiver into an NSDate object.

您还没有设置日期组件的calendar,所以.date 为nil。阅读 the answers on this question 了解更多关于解包选项的信息。

关于ios - 为什么我得到 "fatal error: unexpectedly found nil while unwrapping an Optional value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530054/

相关文章:

ios - 关于 iOS 应用中的唯一标识符

ios - 使用正交滚动行为的水平 uicollectionview 中的大差距

swift - 如何在滚动时同时旋转表格 View 单元格中的所有 View ?

swift - 将远程帧缓冲区流式传输到 NSView

ios - 段错误 11 修复了吗?

ios - Xamarin降低影片大小

ios - 处理 CloudKit 错误

html - 上传多个文件并访问相机

ios - 单击另一个按钮更改按钮背景

ios - 当表格 View 滚动 Swift 时,文本字段变为空