例如这个代码:
func trigramSimilarity(to other: Set<String>) -> Double {
let selfTrigram = trigrams()
let total = selfTrigram.union(other)
let common = selfTrigram.intersection(other)
return total.isEmpty ? 0 : Double(common.count) / Double(total.count)
}
我希望编译器转换为
func trigramSimilarity(to other: Set<String>) -> Double {
let selfTrigram = trigrams()
let total = selfTrigram.union(other)
return total.isEmpty ? 0 : Double(selfTrigram.intersection(other).count) / Double(total.count)
}
通过注意到,如果swift 编译器可以让我编写更简单的代码但避免不必要的计算,那么这let common
是不需要的。total.isEmpty
但直接说出来是否更安全呢?