1

I'm working on an app and I need to know something, because I cannot continue without a solution to my problem. I have an array of the following type:

var samples : [HKSample?]!

Now I want to know if this array contains a specific element and what's the index of that element. When I'm trying to get the index like this

let anotherSample : HKSample = otherSamples.first
let index = samples.indexOf(anotherSample)

I get the following error:

"Cannot convert value of type 'HKSample?' to expected argument type '@noescpae (HKSample?) throws -> Bool'

Please help me!

1 Answer 1

4
let anotherSample : HKSample = otherSamples.first

This is incorrect (and shouldn't compile). first will return HKSample? here.

Given that, you're searching for an HKSample? within an [HKSample?]. The problem is that Optional is not Equatable, so you have to use the predicate form of indexOf:

let index = samples.indexOf { $0 == anotherSample }

(where anotherSample is HKSample?, not HKSample.)

It is true that Optional has an == function available when its underlying type is Equatable, but it isn't itself Equatable because you can't currently conform to a protocol with a where clause. In order to make Optional conform, you'd have to be able to write:

extension Optional: Equatable where Wrapped: Equatable {}

But that's not currently supported in Swift. You'll get:

error: extension of type 'Optional' with constraints cannot have an inheritance clause
Sign up to request clarification or add additional context in comments.

6 Comments

But when I need the type 'HKSample?' and .first returns 'HKSample?' why isn't my approach working?
@MartinR Yeah; I was just writing that :D It suddenly occurred to me that it couldn't be ambiguous.
That sounds a bit complicated. I'm trying to find a workaround for that. :D But thank you very much!
let index = samples.indexOf { $0 == anotherSample } is complicated? That's very normal Swift.
I mean the extension for Optional etc.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.