更改数组中的元素时更改 swift UILabel

Change swift UILabel when change elements in array

我遇到无法解决的问题: 我有 2 个文件,一个是元素数组(名称和图像),另一个文件是我尝试调用数组元素来更改 UILable 中的文本。

第二个文件中数组的代码:

var items: [ItemInfo] = [("AAZ-2", "AAZ-02"), ("BACT01", "Anti-Bacterial"), ("FK01", "Fresh Keeping"), ("mouse", "Anti-Rodents"), ("RIC01", "Anti-VOC"), ("UV01", "UV Protection")]

在另一个文件中,为了从另一个文件访问变量和数组,我创建了这个:

let demoViewController: DemoViewController = DemoViewController()

现在我创建一个函数,从中获取代码以从数组中调用文件

func newLable(){
     if demoViewController.items.enumerated().first(where: {[=13=].element.title == "AAZ-02"}) != nil{
           textLabel.text = "text1"

    }else if demoViewController.items.enumerated().first(where: {[=13=].element.title == "Anti-Bacterial"}) != nil{
               textLabel.text = "tex2"

    }

但每次尝试 运行 应用程序时,当我在第一个(数组元素)和第二个元素之间切换时,我在标签中收到相同的文本(输出是:text1,如代码)。

先谢谢大家的帮助

我想你对"first"的意思有误解。

第一个并不意味着在第一个索引处找到项目,而是找到第一个适合您搜索的项目(在任何索引处).

因此,当您向数组询问 "first" 项时,它满足您的谓词(例如等于 "AAZ-02"),那么无论该项的确切位置如何,它总会找到答案。因此,当您切换前两个项目时,此函数将找到该项目,尽管它位于更高的索引上。这意味着,您的 "else" - 路径将永远不会被执行。

你最好试试这个:

// Pass in your itemInfo you want to search for 
func newLabel(forItem item : ItemInfo) {

     // search the first occurrence of your item
     if demoViewController.items.enumerated().first(where: {[=10=].element.title == item.title}) != nil {

         // if found -> set the itemInfo as the labelTitle
         textLabel.text = item.title
     }
}