Swift TipKit复杂规则用filter报错:该规则不支持filter函数
TipKit规则中使用filter报错:The filter function is not supported in this rule
问题描述
尝试基于TipKit实现提示展示的复杂规则,参考官方示例代码后,完全相同的代码无法编译,在代码行$0.donations.filter { $0.landmarkName != "Wilbere Bowl" }.count > 3处报错:"The filter function is not supported in this rule"。
解决方案
TipKit的Rule闭包仅支持有限的函数和操作,filter不在允许的范围内。可以改用reduce来统计符合条件的捐赠数量,替代filter+count的组合。
修改后的rules部分代码如下:
var rules: [Rule] { #Rule(Self.didViewLandmarkDetail) { $0.donations.reduce(0) { total, donation in donation.landmarkName != "Wilbere Bowl" ? total + 1 : total } > 3 } }
说明
TipKit的规则DSL为了保证性能和兼容性,仅支持特定操作(比如基本算术运算、reduce等),而filter这类会生成新集合的函数不在支持列表中。通过reduce遍历所有捐赠记录,累加符合条件的数量,就能实现原代码的逻辑,同时通过编译。
内容的提问来源于stack exchange,提问作者GuanacoBE
相关产品推荐
相关产品推荐

