[英]The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
[英]Compiler error while declaring an array: compiler is unable to type-check … distinct sub-expressions
我正在使用healthkit并获得读取数据的权限。 当要求5种数据类型时,就可以了。 虽然,如果再添加一个,则会出现错误The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
。 这是代码
let healthkitTypesToRead = NSSet(array: [
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) ?? "",
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass) ?? "",
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) ?? "",
HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) ?? "",
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodPressureDiastolic) ?? "",
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodPressureSystolic) ?? ""
]
)
目前尚不清楚为什么要注射?? ""
?? ""
插入此代码。 这似乎是没有意义的(它说:“如果我不能添加此quantityType,则添加一个字符串,这没有任何意义。)我想你的意思是:“我只是希望将这些添加为非nil ,实际上它们应该是,但我不想添加!
如果我错了,就会崩溃。”如果那是您的意思,那么这就是您的意思:
let healthkitTypesToRead = Set<HKObjectType>([
.quantityType(forIdentifier: .height),
.quantityType(forIdentifier: .bodyMass),
.quantityType(forIdentifier: .heartRate),
.categoryType(forIdentifier: .sleepAnalysis),
.quantityType(forIdentifier: .bloodPressureDiastolic),
.quantityType(forIdentifier: .bloodPressureSystolic),
].compactMap { $0 }
)
但是,这些都是编译时常量。 如果其中任何一个失败,那实际上是编程错误。 那是一点!
是合适的,所以我个人会这样写(但这只是观点和风格的问题):
let healthkitTypesToRead = Set<HKObjectType>([
.quantityType(forIdentifier: .height)!,
.quantityType(forIdentifier: .bodyMass)!,
.quantityType(forIdentifier: .heartRate)!,
.categoryType(forIdentifier: .sleepAnalysis)!,
.quantityType(forIdentifier: .bloodPressureDiastolic)!,
.quantityType(forIdentifier: .bloodPressureSystolic)!,
]
)
注意我已经用Set
替换了NSSet
。 除非您有非常充分的理由,否则不应在此处使用NSSet
。
采用:
protocol HKCustomContainer: Hashable { }
extension HKCategoryTypeIdentifier: HKCustomContainer { }
extension HKQuantityTypeIdentifier: HKCustomContainer { }
let identifierArray: [HKCustomContainer] = [
HKQuantityTypeIdentifier.height,
HKQuantityTypeIdentifier.bodyMass,
HKQuantityTypeIdentifier.heartRate,
HKCategoryTypeIdentifier.sleepAnalysis,
HKQuantityTypeIdentifier.bloodPressureDiastolic,
HKQuantityTypeIdentifier.bloodPressureSystolic
]
let hkObjectTypeArray: [String] = identifierArray.compactMap {
if let qt = $0 as? HKQuantityTypeIdentifier {
return HKObjectType.quantityType(forIdentifier: qt) ?? ""
} else if let ct = $0 as? HKCategoryTypeIdentifier {
return HKObjectType.categoryType(forIdentifier: ct) ?? ""
}
return nil
}
print(Set(hkObjectTypeArray))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.