我有一个简单的条件,如下所示:
func startQueryForActivitySummary() {
func createPredicate() -> NSPredicate? {
let calendar = Calendar.autoupdatingCurrent
var dateComponents = calendar.dateComponents([.year, .month, .day],
from: Date())
dateComponents.calendar = calendar
let predicate = HKQuery.predicateForActivitySummary(with: dateComponents)
return predicate
}
let queryPredicate = createPredicate()
let query = HKActivitySummaryQuery(predicate: queryPredicate) { (query, summaries, error) -> Void in
if let summaries = summaries {
for summary in summaries {
let activeEnergyBurned = summary.activeEnergyBurned.doubleValue(for: HKUnit.kilocalorie())
let activeEnergyBurnedGoal = summary.activeEnergyBurnedGoal.doubleValue(for: HKUnit.kilocalorie())
let activeEnergyBurnGoalPercent = round(activeEnergyBurned/activeEnergyBurnedGoal)
print(activeEnergyBurnGoalPercent)
}
}
}
healthStore?.execute(query)
}
f有副作用,如果k与0不同,则不能调用。我可以依赖布尔短路,以便编译器永远不会调用f吗?当然,我可以将if移到外面以保证在k!= 0时永远不会调用f,但这更短。
答案 0 :(得分:3)
8.14逻辑AND运算符[expr.log.and]
- &&操作员组从左到右。操作数都在上下文中转换为bool(第7条)。如果两个操作数都为真,则结果为true,否则为false。不像&,&&保证从左到右的评估:如果第一个操作数为假,则不评估第二个操作数。
醇>
因此,如果k
不等于0
,则符合标准的编译器将不会调用f
。