如何找到数组中特定元素的索引

时间:2018-09-22 04:47:14

标签: swift

我有NSMutablearray。

 var answers1 = NSMutableArray ()

这是数组。

我已经有了数组。现在数组如下。

("","","","sam","jeena")

这是数据。现在,我需要检查answer1中是否包含元素“”,并且需要获取字符串为“”的索引。如果索引已获得,则显示警报。

示例:-“”-在索引0,1,2中可用。因此,迭代NSMutablearray,然后首先将警报显示为:-请从index0中选择数据。

实际上我在这里有一个tableview(分组)。所以对于每个部分我都选择了一个答案,就像每个答案都附加在数组中一样。

所以我需要检查答案数组,是否从每个部分中选择了一个单元格。如果没有,则显示为:-

   print("Please select item at",(section))

                    let questionModel = questionViewModel.titleForHeaderInSection(atsection: section)
                    print(questionModel.question)

                    let controller = UIAlertController(title: "Please Select any option from question", message:(questionModel.question), preferredStyle: .alert)
                    // Create the actions
                    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
                        UIAlertAction in
                        NSLog("OK Pressed")
                        //   self.viewDidLoad()
                        //

                    }
                    controller.addAction(okAction)
                    //  controller.addAction(cancel)

                    self.present(controller, animated: true, completion: nil)


          How to do?

2 个答案:

答案 0 :(得分:2)

而不是项目filter的索引

let array = ["","","","edsdfg","fhjuyj","dfhjg"] 
let emptyIndices = array.indices.filter{ array[$0].isEmpty } // [0, 1, 2]

答案 1 :(得分:0)

您可以编写一个自定义函数,类似这样的方法来查找索引。

func allIndices(ofArray: [String], forElement: String) -> [Int] {
    var indices = [Int]()
    for (index, element) in str.enumerated() {
        if element == forElement {
            indices.append(index)
        }
    }
    return indices
}

您可以将其称为

let result = allIndices(ofArray: stringArray, forElement: "")
相关问题