提问者:小点点

Swift:表达式类型不明确,没有更多上下文


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

共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让检查HKObjectType,则效果更好。quantityTypeForIdentifier实际上在创建集合之前返回一个值