Search code examples
arraysswiftif-statementuitextfielduilabel

how to set up a search with an "if" statement for arrays, very basic app (swift)


I'm working on a basic app which has a listArray with ~1400 items, each with 3 properties (icao, callsign, image). It has 2 outlets: a "textField" and a "label". With my custom keyboard(buttons) i can write 3 characters into my "textField". And if these 3 characters are matching with the icao item of my listArray, then I would like the callsign item to be shown in my "label". Is there a way to do it with an "if" statement? I would like to see "AMERICAN" in the "label". Here is what I have: my xcode and simulator screens

  @IBOutlet var ICAOtextField: UITextField!
@IBOutlet var callsignTextLabel: UILabel!

var updatedICAOtextField = ""
var listArray = [list]()

override func viewDidLoad() {
    super.viewDidLoad()
    setUpList()
}

private func setUpList() {

listArray.append(list(icao: "AAB", callsign: "A-B-G", image: "BELGIUM"))
listArray.append(list(icao: "AAC", callsign: "ARMYAIR", image: "UK"))
listArray.append(list(icao: "AAF", callsign: "AZUR", image: "FRANCE"))
listArray.append(list(icao: "AAL", callsign: "AMERICAN", image: "USA"))
}

@IBAction func abcButton(_ sender: UIButton) {
    
    updatedICAOtextField = ICAOtextField.text! + sender.currentTitle!
    ICAOtextField.text = updatedICAOtextField
    
    if updatedICAOtextField.count > 3 {
        ICAOtextField.text = ""
    }
    
    if ICAOtextField.text ==                           {
        
        callsignTextLabel.text = "            "
    }
    
}

Solution

  • @IBAction func abcButton(_ sender: UIButton) {

        updatedICAOtextField = ICAOtextField.text! + (sender.titleLabel?.text)!
        ICAOtextField.text = updatedICAOtextField
        
        if updatedICAOtextField.count >= 3 {
            let index = listArray.firstIndex { (list) -> Bool in
                if list.icao == updatedICAOtextField {
                    return true
                }
                return false
            }
            if index != nil {
                callsignTextLabel.text = listArray[index!].callsign
            }
            ICAOtextField.text = ""
        }
    }