Search code examples
xcode7downcast

Downcast error in Xcode 7


In xcode 6, this code worked fine, but in Xcode 7GM, I am getting an error that states:

Downcast from ‘[UILocalNotification]? to ‘[UILocalNotification]’ only unwraps optionals; did you mean to use ‘!’?

The error occurs for the line where I have put two asterisks. In Xcode, there is also a little red triangle under the a of the as! portion.

func removeItem(item: TodoItem) {
    **for notification in (UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification]) { // loop through notifications...
        if (notification.userInfo!["UUID"] as! String == item.UUID) { // ...and cancel the notification that corresponds to this TodoItem instance (matched by UUID)
            UIApplication.sharedApplication().cancelLocalNotification(notification) // there should be a maximum of one match on UUID
            break
        }
    }

Solution

  • In Xcode 6 scheduledLocalNotifications is declared as [AnyObject]! (downcast required).
    In Xcode 7 scheduledLocalNotifications is declared as [UILocalNotification]? (has only to be unwrapped)

    I recommend to use optional bindings

    func removeItem(item: TodoItem) {
      if let scheduledLocalNotifications = UIApplication.sharedApplication().scheduledLocalNotifications {
       for notification in scheduledLocalNotifications { // loop through notifications...
        if (notification.userInfo!["UUID"] as! String == item.UUID) { // ...and cancel the notification that corresponds to this TodoItem instance (matched by UUID)
            UIApplication.sharedApplication().cancelLocalNotification(notification) // there should be a maximum of one match on UUID
            break
        }
      }
    }