ios - Swift 4 - 对成员 '>' (iOS 11) 的模糊引用
<p><p>在转换为 Swift 4 语法后,我收到了这个误导性错误消息。</p>
<blockquote>
<p>Ambiguous reference to member '>'</p>
</blockquote>
<p>在这行代码上:</p>
<pre><code>redCount = alerts!.filter { $0.dangerLevels.filter { $0.level.value == 4 }.count > 0 }.count
</code></pre>
<p>完整的上下文代码:</p>
<pre><code>alerts = realm.objects(Alerts).filter(NSPredicate(format: "department != nil")).sorted(byKeyPath: "departmentNumber")
redCount = alerts!.filter { $0.dangerLevels.filter { $0.level.value == 4 }.count > 0 }.count
</code></pre>
<p>错误信息根本不明确,我可以给一些提示吗?</p>
<p>请记住,<strong>alerts</strong> 的类型是 <code>Results<Alert>?</code> </p>
<p>和 <strong>dangerLevel</strong> 声明如下: <code>let dangerLevels = List<DangerLevel>()</code></p>
<p><strong>编辑:</strong> </p>
<p>这里有一些关于闭包内类型的附加信息。</p>
<pre><code>let level = RealmOptional<Int>()
</code></pre>
<p>值来自 RealmOptional</p>
<pre><code>public var value: T? {
get {
return underlyingValue.map(dynamicBridgeCast)
}
set {
underlyingValue = newValue.map(dynamicBridgeCast)
}
}
</code></pre>
<p><strong>编辑 2:</strong>我已经重写了语法以获得更好的可读性,但这是我的结果:</p>
<pre><code>redCount = alerts!.filter { $0.dangerLevels.contains { ($0.level.value as! Int) == 4 } }.count
</code></pre>
<p> <a href="/image/C9o74.png" rel="noreferrer noopener nofollow"><img src="/image/C9o74.png" alt="enter image description here"/></a> </p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p><code>value</code> 是一种通用方法,当与文字(即没有定义类型的东西)进行比较时,编译器很难确定在那里推断出什么类型。一种解决方法是将 <code>as Int</code> 添加到表达式的一侧:</p>
<p>(为了可读性略有改写)</p>
<pre><code>let alerts = realm.objects(Alerts).filter(NSPredicate(format: "department != nil")).sorted(byKeyPath: "departmentNumber")
let isRedLevel: (DangerLevel) -> Bool = { dangerLevel in
($0.level.value as Int) == 4
}
let hasRedLevels: (Alert) -> Bool = { alert in
alert.dangerLevels.contains(where: isRedLevel)
}
redCount = alerts!.filter(hasRedLevels).count
</code></pre>
<p>也可以定义一个常量:</p>
<pre><code>let redAlertType: Int = 4
</code></pre>
<p>并使用它代替文字 <code>4</code>.</p></p>
<p style="font-size: 20px;">关于ios - Swift 4 - 对成员'>' (iOS 11) 的模糊引用,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/46523499/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/46523499/
</a>
</p>
页:
[1]