Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 包含零值的Swift Array.indexOf_Ios_Arrays_Swift - Fatal编程技术网

Ios 包含零值的Swift Array.indexOf

Ios 包含零值的Swift Array.indexOf,ios,arrays,swift,Ios,Arrays,Swift,我正在开发一个应用程序,我需要知道一些事情,因为如果没有问题的解决方案,我无法继续。我有一个以下类型的数组: var samples : [HKSample?]! 现在我想知道这个数组是否包含一个特定的元素,以及该元素的索引是什么。当我试图得到这样的索引时 let anotherSample : HKSample = otherSamples.first let index = samples.indexOf(anotherSample) 我得到以下错误: "Cannot convert v

我正在开发一个应用程序,我需要知道一些事情,因为如果没有问题的解决方案,我无法继续。我有一个以下类型的数组:

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?
。问题是,
可选
不可
相等
,因此必须使用
索引的谓词形式

let index = samples.indexOf { $0 == anotherSample }
(其中,
另一个样本
HKSample?
,而不是
HKSample

诚然,
Optional
在其基础类型为
Equatable
时有一个可用的
=
函数,但它本身不是
Equatable
,因为您当前无法遵守带有
where
子句的协议。为了使
可选
符合要求,您必须能够编写:

extension Optional: Equatable where Wrapped: Equatable {}
但Swift目前不支持这一点。您将获得:

error: extension of type 'Optional' with constraints cannot have an inheritance clause
这是不正确的(不应该编译)
first
将在此处返回
HKSample?

鉴于此,您正在
[HKSample?]
中搜索
HKSample?
。问题是,
可选
不可
相等
,因此必须使用
索引的谓词形式

let index = samples.indexOf { $0 == anotherSample }
(其中,
另一个样本
HKSample?
,而不是
HKSample

诚然,
Optional
在其基础类型为
Equatable
时有一个可用的
=
函数,但它本身不是
Equatable
,因为您当前无法遵守带有
where
子句的协议。为了使
可选
符合要求,您必须能够编写:

extension Optional: Equatable where Wrapped: Equatable {}
但Swift目前不支持这一点。您将获得:

error: extension of type 'Optional' with constraints cannot have an inheritance clause

但是当我需要输入'HKSample'并且.first返回'HKSample'时,为什么我的方法不起作用?@MartinR Yeah;我刚刚在写:D我突然意识到它不可能是模棱两可的。这听起来有点复杂。我正试图找到一个解决办法D但是非常感谢你
let index=samples.indexOf{$0==anotherSample}
很复杂吗?这是非常正常的Swift。我指的是可选等的扩展。但是当我需要类型“HKSample”时。首先返回“HKSample”?为什么我的方法不起作用?@MartinR Yeah;我刚刚在写:D我突然意识到它不可能是模棱两可的。这听起来有点复杂。我正试图找到一个解决办法D但是非常感谢你
let index=samples.indexOf{$0==anotherSample}
很复杂吗?这是非常正常的Swift。我是指可选的扩展等。