Macos Swift通知中心可以';t展开可选。无
我正在编写一个简单的程序 我想在mac os x上显示通知 这是我的密码Macos Swift通知中心可以';t展开可选。无,macos,notifications,swift,center,Macos,Notifications,Swift,Center,我正在编写一个简单的程序 我想在mac os x上显示通知 这是我的密码 import Foundation import Cocoa var notification:NSUserNotification = NSUserNotification() notification.title = "TEST" notification.subtitle = "TTTT" var notificationcenter:NSUserNotificationCenter = NSUserNotif
import Foundation
import Cocoa
var notification:NSUserNotification = NSUserNotification()
notification.title = "TEST"
notification.subtitle = "TTTT"
var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
if(notificationcenter != nil) {
notificationcenter.scheduleNotification(notification)
}
该代码生成成功,但当停止运行代码时
fatal error: Can't unwrap Optional.None
var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
我能做什么您之所以会得到这个结果,是因为您尝试了“展开可选”(可以为零),您可以这样做:
if let notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() {
notificationcenter.scheduleNotification(notification)
}
您正在将变量声明为显式
var notificationcenter:NSUserNotificationCenter
这意味着它不能为零
但是这个
NSUserNotificationCenter.defaultUserNotificationCenter()
can失败,意味着它返回nil
试试这个
var notificationcenter: NSUserNotificationCenter? = NSUserNotificationCenter.defaultUserNotificationCenter()
然后,您的var是可选的,现在可以将其设置为零