Swift 2에서는 이런 식으로 자주 쓰던 타입 중 다수가 OptionSetType 프로토콜을 구현하도록 바뀌었습니다. 그래서 배열과 비슷한 문법을 지원하며, 질문의 예제는 이렇게 작성할 수 있습니다.
let notificationOptions = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationOptions)
관련해서, 옵션 집합에 어떤 옵션이 있는지 확인할 때도 더는 비트 AND 뒤에 nil 검사를 할 필요가 없습니다. 대신 배열에 원소가 있는지 확인하듯 그 집합에 원하는 값이 들어 있는지 물으면 됩니다.
let notificationOptions = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
if notificationOptions.types.contains(.Alert) {
// handle this option
}
Swift 3에서는 예제를 이렇게 쓰세요:
let notificationOptions = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(notificationOptions)
그리고
let notificationOptions = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
if notificationOptions.types.contains(.alert) {
// handle this option
}
영어에서 번역·원문 보기Swift 2 changed many of the types commonly used this way to implement the OptionSetType protocol instead. Consequently they support a syntax resembling arrays, so your particular example can be written like this.
let notificationOptions = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationOptions)
Relatedly, checking whether an option belongs to an option set no longer requires a bitwise AND followed by testing for nil. Instead, ask whether that set contains the particular value, much as you would check an array for an element.
let notificationOptions = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
if notificationOptions.types.contains(.Alert) {
// handle this option
}
For Swift 3, write those examples this way:
let notificationOptions = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(notificationOptions)
and
let notificationOptions = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)
if notificationOptions.types.contains(.alert) {
// handle this option
}