Swift:表达式的类型没有更多的上下文

时间:2015-10-24 14:51:52

标签: swift

let healthWrite = Set(arrayLiteral:[
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned),
    HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning),
    HKQuantityType.workoutType()
])

1 个答案:

答案 0 :(得分:1)

构造函数想要一个数组文字而不是一个数组,所以你用这样的东西初始化

let healthWrite = Set(arrayLiteral:
     HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,
     HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
     HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!,
     HKQuantityType.workoutType()
     )

有关数组和数组文字的更多信息 https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

编辑:

这是可选的值让你感到悲伤而不是" []"

let healthWrite = Set([
            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,
            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!,
            HKQuantityType.workoutType()]
            )

更好的是,如果您使用guardif let检查HKObjectType.quantityTypeForIdentifier在创建集合之前是否实际返回了值