【问题标题】:How to check what number array a string is in. using swift如何检查字符串在哪个数字数组中。使用 swift
【发布时间】:2015-06-01 02:45:21
【问题描述】:

如何让文本字段输入返回文本所在的数组索引,而不像下面那样手动执行,因为数组中有数百个项目(颜色只是一个示例)?

@IBOutlet weak var label:UILabel

@IBOutlet weak var textField:UITextField


var arrayOfColors:[String] = ["Blue", "Black", "Yellow", "Purple"]


if textFeild.text == "Blue" {

println("array index 0")
}

else if textFeild.text == "Yellow" {

println("array index 3")
}

【问题讨论】:

    标签: ios arrays xcode swift dictionary


    【解决方案1】:

    如果您多次具有相同的值,您应该遍历数组并只打印索引或索引。

    find 函数只会返回第一次出现的搜索文本。

    var arrayOfColors:[String] = ["Blue", "Black", "Yellow", "Purple", "Yellow"]
    
    for var i = 0; i < arrayOfColors.count; i++ {
        if arrayOfColors[i] == textField.text { 
            println("The index is \(i)") // assuming textField.text is "Yellow" it will print "The index is 2" and "The index is 4"
        }
    }
    

    【讨论】:

    • 这个答案比它需要的效率低。另外,“黄色”应该是文本字段的文本。
    • 为什么说这个答案效率低下?是的"Yellow"应该修改为textField.text,但是我不能说它将打印索引为2
    • 因为您可以使用 find 功能进行更高效的搜索。
    • 是的,但是如果我有这个数组["Blue", "Black", "Yellow", "Purple", "Yellow"]find 函数不会返回我可能需要的“黄色”的第二个索引,所以它取决于需要什么的上下文.
    • 好的,这很公平。我会在您的回答中指定...但是,“黄色”应该更改为 textField.text。
    【解决方案2】:

    这给了你一个可选的,所以准备好在必要时处理 nil

    find(arrayOfColors, textFeild.text!) //returns the index (0) if text is "Blue"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 2012-03-16
      • 1970-01-01
      相关资源
      最近更新 更多