Nikita Zernov
Nikita Zernov

Reputation: 5635

Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserNotificationType operands

I am trying to register my application for local notifications this way:

UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))

In Xcode 7 and Swift 2.0 - I get error Binary Operator "|" cannot be applied to two UIUserNotificationType operands. Please help me.

Upvotes: 194

Views: 47248

Answers (4)

Mick MacCallum
Mick MacCallum

Reputation: 130193

In Swift 2, many types that you would typically do this for have been updated to conform to the OptionSetType protocol. This allows for array like syntax for usage, and In your case, you can use the following.

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)

And on a related note, if you want to check if an option set contains a specific option, you no longer need to use bitwise AND and a nil check. You can simply ask the option set if it contains a specific value in the same way that you would check if an array contained a value.

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)

if settings.types.contains(.Alert) {
    // stuff
}

In Swift 3, the samples must be written as follows:

let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)

and

let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)

if settings.types.contains(.alert) {
    // stuff
}

Upvotes: 387

CodeSteger
CodeSteger

Reputation: 127

This has been updated in Swift 3.

        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)

Upvotes: 2

Ah Ryun Moon
Ah Ryun Moon

Reputation: 370

What worked for me was

//This worked
var settings = UIUserNotificationSettings(forTypes: UIUserNotificationType([.Alert, .Badge, .Sound]), categories: nil)

Upvotes: 7

Bobj-C
Bobj-C

Reputation: 5426

You can write the following:

let settings = UIUserNotificationType.Alert.union(UIUserNotificationType.Badge)

Upvotes: 35

Related Questions