iOS Question Object type behavior on B4A/B4i

Alessandro71

Well-Known Member
Licensed User
Longtime User
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?
 

Star-Dust

Expert
Licensed User
Longtime User
B4X:
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
 
Upvote 0

Alessandro71

Well-Known Member
Licensed User
Longtime User
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
 
Upvote 0

Star-Dust

Expert
Licensed User
Longtime User
in b4i you always have to use array of object and inside put the type you prefer
 
Upvote 0

Alessandro71

Well-Known Member
Licensed User
Longtime User
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?
 
Upvote 0

Star-Dust

Expert
Licensed User
Longtime User
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
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
other:
B4X:
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
 
Upvote 0
Top