我正在开发一个应用程序,因此我需要了解一些东西,因为如果没有解决问题的方法,我将无法继续。我有以下类型的数组:
var samples : [HKSample?]!
现在,我想知道此数组是否包含特定元素,以及该元素的索引是什么。当我试图获得这样的索引
let anotherSample : HKSample = otherSamples.first
let index = samples.indexOf(anotherSample)
我收到以下错误:
"Cannot convert value of type 'HKSample?' to expected argument type '@noescpae (HKSample?) throws -> Bool'
请帮我!
最佳答案
let anotherSample : HKSample = otherSamples.first
这是不正确的(并且不应该编译)。
first
将在此处返回HKSample?
。鉴于此,您正在
HKSample?
中搜索[HKSample?]
。问题在于Optional
不是Equatable
,因此您必须使用indexOf
的谓词形式:let index = samples.indexOf { $0 == anotherSample }
(其中
anotherSample
是HKSample?
,而不是HKSample
。)当
Optional
的基础类型为==
时,确实可以使用Equatable
函数,但它本身不是Equatable
,因为您当前无法遵循带有where
子句的协议。为了使Optional
符合要求,您必须能够编写:extension Optional: Equatable where Wrapped: Equatable {}
但是Swift目前不支持该功能。你会得到:
error: extension of type 'Optional' with constraints cannot have an inheritance clause
关于ios - Swift Array.indexOf包含零值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35893952/