How to get value and id_value for PushRow in Swift4

I use xCode 9, swift 4 and "Eureka form library" for my project.



**The situation**



I have a list of cars with name and unique ID associated this way: 0 - ANY, 1 - VW, 7 - AUDI, 20 - MAZDA



var name_cars: [String] = ["ANY","VW","AUDI","MAZDA"]



var id_cars:[Int] = [0, 1, 7, 20]



I also have a form with "PushRow" and "ButtonRow".

On click to the button I want to print the selected car name and ID.

I was able to print the car's name but not the ID.



import UIKit

import Eureka



class myPage: FormViewController {



var cars: [String] = ["ANY","VW","AUDI","MAZDA"]

var id_cars:[Int] = [0, 1,7,20]


var selected_car: String = "ANY" //default car

var selected_car_id: Int = 0 //default id car


override func viewDidLoad() {

super.viewDidLoad()

create_form()

}


func create_form(){

form

+++ Section("List")

//list

<<< PushRow<String>() {

$0.title = "Cars"

$0.options = cars

$0.value = "ANY"

$0.tag = "list_element"

$0.selectorTitle = "Choose car"

$0.onChange { [unowned self] row in

self.selected_car = row.value!

self.selected_car_id = ??? // **what should it be here in order to get the ID**

}

}

//button

<<< ButtonRow("Button1") {row in

row.title = "Get Value on Console"

row.onCellSelection{[unowned self] ButtonCellOf, row in

print ("Car selected = ",self.selected_car, " and Id_Car_Selected = ",self.selected_car_id)

}

}

}



}

Answered by alexfromhome in 322562022

Thanks a lot for your answers. After more digging I found a complete solution here https://stackoverflow.com/questions/51423153/how-to-get-value-and-id-value-for-pushrow-in-swift4

If I understand your code, you should set as :


  self.selected_car_id = self.id_cars[ row.value!] // **what should it be here in order to get the ID**


But really, I find your code a bit complex for something that seems simple, due to Eureka (I don't use it).


Have you seen this tutorial :

h ttps://www.raywenderlich.com/156849/eureka-tutorial-start-building-easy-ios-forms

Thanks Claude31, but row.value return the selected element from "cars".

So row.value is not number.

row.value is "ANY", "VW", "AUDI" or "MAZDA"


Yes, I know this tutorial.

Well, I don't know Eurela.


But this should work (even if a bit clunky):


get the index of row.value

if let index = self.cars.index(of: row.value!) {
     self.selected_car_id = self.id_cars[index]
}
Accepted Answer

Thanks a lot for your answers. After more digging I found a complete solution here https://stackoverflow.com/questions/51423153/how-to-get-value-and-id-value-for-pushrow-in-swift4

Proposed solution on SO is clearly a good design.


Just for curiosity, did the code I proposed work ?

How to get value and id_value for PushRow in Swift4
 
 
Q