Alexandr Smushko Alexandr Smushko - 8 days ago 8
iOS Question

Get object from array by index, that is getting from another array

There are two arrays: idArrayInt and nameArrayString. I need to get an object from first array by index, that I get from second. I know that it is pretty simple, but I'm new at IOS development and don't understand how to implement it.

var idArray = [Int]() //for example 1 2 3
var nameArray = [String]() // for example "one" "two" "three"
var ident: Int!

@IBAction func btnNext_click(_ sender: AnyObject) {

var nameString = lblUnitType.text
var index = nameArray.index(of: nameString) //Cannot invoke 'index' with an argument list of type '(of: String?)'
ident = idArray[index] //something like that by I don't sure
}

Answer

lblUnitType.text and the result of index(of: are optionals, you need to unwrap them preferable with optional bindings:

if let nameString = lblUnitType.text, let index = nameArray.index(of: nameString), index < idArray.count { 
    ident = idArray[index] 
}
Comments