【问题标题】:Swift NotificationCenter Can't unwrap Optional.NoneSwift NotificationCenter 无法打开 Optional.None
【发布时间】:2014-06-30 06:17:37
【问题描述】:

我正在编写简单的程序 我想在 mac os x 上显示通知

这是我的代码

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()

我能做什么

【问题讨论】:

    标签: macos notifications swift center


    【解决方案1】:

    你得到这个是因为你尝试 unwrap optional 可以是 nil,你可以这样做:

    if let notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() {
        notificationcenter.scheduleNotification(notification)
    }
    

    【讨论】:

      【解决方案2】:

      您将变量声明为显式。

      var notificationcenter:NSUserNotificationCenter
      

      这意味着它不能为零

      但是这个

      NSUserNotificationCenter.defaultUserNotificationCenter()
      

      can fail,这意味着它返回 nil


      试试这个

      var notificationcenter: NSUserNotificationCenter? = NSUserNotificationCenter.defaultUserNotificationCenter()
      

      你的 var 然后是可选的,现在它可以设置为 nil

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多