Swift Type推理混淆?

时间:2015-09-03 09:35:09

标签: swift2 type-inference xcode7-beta6

这会将UIUserNotificationType数组分配给UIUserNotificationType的变量。这应该不起作用:

1)

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

这是[UIUserNotificationType]

的类型

2)

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

尝试分配失败按预期失败:

3)

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

尝试将[UIUserNotificationType]分配给UIUserNotificationType显然不起作用,为什么1)会编译?

1 个答案:

答案 0 :(得分:1)

[.Alert, .Badge, .Sound]的语法可用于两种不同的目的。它可以为Array<UIUserNotificationType>

定义OptionTypeSet或创建位掩码UIUserNotificationType

结果取决于声明的赋值变量类型。

OptionSetType

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

userNotificationTypes实际上是一个OptionSetType位掩码,它从C&#39}的角度看起来像(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound)

阵列

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

userNotificationTypesUIUserNotificationType类型的数组。