0

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     
}
2
  • Sounds like you would be better off using a dictionary than an array Commented Nov 24, 2016 at 10:57
  • or an array of a custom struct, containing just the ID and name Commented Nov 24, 2016 at 21:43

2 Answers 2

2

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] 
}
Sign up to request clarification or add additional context in comments.

1 Comment

@NiravD Thanks, I added a where clause
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.