VYT
VYT

Reputation: 1071

Adding optional tuple to the array

I have function returning the optional tuple

(Range<String.Index>?, Range<String.Index>?). 

Then, I need to add this tuple to the array of tuples which I declares as

var arrayOftuples = [(Range<String.Index>, Range<String.Index>)]()

I am adding the tuple to the array like this

arrayOftuples += [mytuple]

It gives me note that the operator += cannot be applied to the operands

 [(Range<String.Index>, Range<String.Index>)]

and

 [(Range<String.Index>?, Range<String.Index>?)]

When I make the declaration of the array with optional

var arrayOftuples = [(Range<String.Index>?, Range<String.Index>?)]()

there is no more complains. But, at the end, I need to use the startIndex and endIndex from the tuples from the array, and when I try to get it like this

let myrange = arrayOftuples.first!.0.startIndex..< arrayOftuples.first!.0.endIndex

I have the complain that value of type

Range<String.Index>? 

has no member startIndex.

As I can understand, if I want to get startIndex and endIndex from the tuples, I need to use the array without optionals,

var arrayOftuples = [(Range<String.Index>, Range<String.Index>)]()

but then I need somehow to add from optional tuples only that which are not (nil, nil). When adding the tuple like this

arrayOftuples += [mytuple!]

it is not accepting this. If I use the condition like this

 if mytuple != (nil, nil)
 {
    arrayOftuples += [mytuple]
 }

it is also not working. Complain is that operator != cannot be applied. How to solve the problem?

Upvotes: 0

Views: 143

Answers (1)

Stefan Salatic
Stefan Salatic

Reputation: 4513

The functions returns optionals probably with a reason. You need to check if those optionals are not nil first, then unwrap them and insert them into the array. After that you shouldn't have any issues.

You can unwrap them like this

if let t1 = touple.0, t2 = touple.1 {
    let unwraped = (t1, t2)
}

Upvotes: 1

Related Questions