Mismatch error

A method returns and array, I need only and specific item of the array

var result() as integer = MethodReturnsArray()

' value needed is returned in array(0), for exemple
var theValue as integer
theValue = result(0) ' that's ok

' How to get theValue without defining the new variable: result?
theValue = MethodReturnsArray() 'normal error
theValue = MethodReturnsArray()(0) 'error
theValue = (MethodReturnsArray())(0) 'error

or, I’m comfused and is not possible to get only a specific item of the returned array?

It may be better to not return an array at all then and return just the one you need?

Or you add a custom method that does what you neeed?

I don’t think you can directly use the function returned array.

Why not just use the MethodReturnsArray(0) item?

If it’s because the MethodReturnsArray is a Method and should not be called often or twice, maybe it’s in this case better to go with the theValue = result(0) solution? :slight_smile:

Sadly Xojo does not have a way

You could open a feature request asking Xojo to create a new method for Arrays
like: Item(index As Integer) As Variant

So you could write expressions as theValue = MethodReturnsArray.Item(0)

1 Like

I guess you could write a class that mimmics an array and provides somewhat that functionality.

Echoing Rick’s suggestion, you can use an extension method to achieve what you’re looking for:

Public Function Item(extends theArray() as integer, index as integer) As integer
  return theArray(index)
End Function

This will let you do the following in code:

dim myInteger as integer

myInteger=MethodReturnsArray.Item(2)

Unfortunately, there’s no generic way to do this in Xojo such that it applies to all array; you’ll have to do this for each array type. But it’s better than nothing.

At the compiler level Xojo can do it in an agnostic and optimized way. That’s why a feature request is great. If the array is typed it solves the item for such type, any non obvious type could end as a Variant item.

E.g. A mixed Array(0, 1, “whatever”).Item(2) should return a Variant(“whatever”) string.

Thanks all, for my case, the easy way is still that I used.
I only wandered if there was a more compact syntax.

Good idea,

Good idea Eric, but i look for a more compact syntax, that is still more code.

There is a second approach which is a little less code on the front end, but doesn’t give you the kind of reusable functionality that the Extends approach does.

Set up a pair of methods like this:

Public Function MethodReturnsArray() As integer()
  return array(1,2,3)
End Function


Public Function MethodReturnsArray(index as integer) As integer
  dim theArray() as integer
  
  theArray=MethodReturnsArray
  
  return theArray(index)
End Function

This will let you do the following:

dim myIntegers() as integer

myIntegers = MethodReturnsArray

dim aSingleInteger as integer

aSingleInteger = MethodReturnsArray(2)

That’s as simple as it’s going to get in Xojo.