0

This assigns an array of UIUserNotificationType to a variable of UIUserNotificationType. This should not work:

1)

var userNotificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
print(userNotificationTypes.dynamicType) // UIUserNotificationType

Here is the type of [UIUserNotificationType]

2)

let intermidiate = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
print(intermidiate.dynamicType) // Array<UIUserNotificationType>

Attempting to assign it fails as expected:

3)

userNotificationTypes = intermidiate // Cannot assign a value of type '[UIUserNotificationType]' to a value of type 'UIUserNotificationType'

Attempting to assign [UIUserNotificationType] to UIUserNotificationType obviously does not work, so why does 1) compiles ?

Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151

1 Answers1

1

The syntax for [.Alert, .Badge, .Sound] can be used for 2 different purposes. It can define an Array<UIUserNotificationType> or create bit mask populated OptionTypeSet for UIUserNotificationType

The result is dependent on the declared type of assignment variable.

OptionSetType

let userNotificationTypes: UIUserNotificationType = [.Alert, .Badge, .Sound]

userNotificationTypes is actually an OptionSetType bit mask, which is from C's point of view looks like (UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound)

Array

let userNotificationTypes: [UIUserNotificationType] = [.Alert, .Badge, .Sound]

userNotificationTypes is Array of UIUserNotificationType types.

Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151
  • Same syntax produces 2 different results based on the assignment type. That's a bit confusing IMHO. More info here http://stackoverflow.com/a/31099051/48062 – Maxim Veksler Sep 03 '15 at 10:12
  • 1
    The bracket syntax `[..., ..., ..., ...]` for initializing a type is called an `ArrayLiteral` and you can conform to the protocol `ArrayLiteralConvertible` to initialize your own type with an `ArrayLiteral`. `Arrays`, `Sets` and types which conform to `OptionSetType` are by default `ArrayLiteralConvertible`. – Qbyte Sep 03 '15 at 17:26