The following sample code works fine in B4A, but gives this error in B4i on line 2
Cannot cast type: {Type=String,Rank=1, RemoteObject=True} to: {Type=Object,Rank=1, RemoteObject=True}
B4X:
Private Sub TestIndex
IndexOf(Array As String("1", "2", "3"), "2")
End Sub
'index value in array
'-1 if not found
Public Sub IndexOf(values() As Object, value As Object) As Int
Dim rc As Int = -1
For i = 0 To values.Length - 1
If (values(i) = value) Then
rc = i
Exit
End If
Next
Return rc
End Sub
Is there a way to write the IndexOf sub on B4i so that it can be type-agnostic?
Private Sub TestIndex
Log(IndexOf(Array As Object("1", "2", "3"), "2"))
End Sub
'index value in array; -1 if not found
Public Sub IndexOf(values() As Object, value As Object) As Int
Dim rc As Int = -1
For i = 0 To values.Length - 1
If (values(i) = value) Then
rc = i
Exit
End If
Next
Return rc
End Sub
The array of strings was just an example: the real world usage would be with arrays of different types, hence the need for Object type in the Sub definition
I have several arrays, of various types, already declared in various places, on which I need to use IndexOf.
should I convert all of them to generic object arrays?
I have several arrays, of various types, already declared in various places, on which I need to use IndexOf.
should I convert all of them to generic object arrays?
In several b4i libraries I had to do this because otherwise it didn't work.
objective C is strongly typed so it differs from what we can do with B4A which is Java based which has a much more flexible casting system
Public Sub TestIndex
Log(IndexOf(Array As Object("1", "2", "3"), "2"))
' Log(IndexOf(Array As String("1", "2", "3"), "2"))
End Sub
'index value in array; -1 if not found
Public Sub IndexOf(Values() As Object, Value As Object) As Object
Dim idx As Int
For Each v As Object In Values
If v = Value Then Return idx : idx = idx + 1
Next
Return -1
End Sub