2014-06-30 30 views
1

我編寫簡單的程序 我想表明在Mac OS通知X斯威夫特通知中心無法解開Optional.None

這是我的代碼

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

我能做些什麼

回答

0

你得到ŧ他因爲你嘗試打開可選項,可以是零,你可以這樣做:

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

你聲明一個變量爲顯式。

var notificationcenter:NSUserNotificationCenter 

這意味着它不能是零

但這

NSUserNotificationCenter.defaultUserNotificationCenter() 

可以失敗,這意味着它然後返回nil


試試這個

var notificationcenter: NSUserNotificationCenter? = NSUserNotificationCenter.defaultUserNotificationCenter() 

你的變種是那麼可選,現在可以設置成零