AlIon
AlIon

Reputation: 367

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     
}

Upvotes: 0

Views: 90

Answers (2)

itechnician
itechnician

Reputation: 1655

You can learn in this playground as shown. enter image description here

Also, in your case you can refer dictionaries. enter image description here

Upvotes: 1

vadian
vadian

Reputation: 285082

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] 
}

Upvotes: 2

Related Questions