Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 将id中的数组字符串值与Swift 3中的索引匹配_Arrays_Swift - Fatal编程技术网

Arrays 将id中的数组字符串值与Swift 3中的索引匹配

Arrays 将id中的数组字符串值与Swift 3中的索引匹配,arrays,swift,Arrays,Swift,我有一个数组 public var options = [String]() // VALUES = John-34 , Mike-56 , Marry-43 etc.. 而且我有功能 public func getIndex(id : Int){ if let index = options.contains("-\(id)".lowercased()) { selectedIndex = index print("\(op

我有一个数组

public var options = [String]()
// VALUES = John-34 , Mike-56 , Marry-43 etc..
而且我有功能

 public func getIndex(id : Int){

        if let index = options.contains("-\(id)".lowercased()) {
            selectedIndex = index
            print("\(options[index])"). 
        }
    }
我想用我的函数获取所选索引,如

getIndex(id:34)//必须显示John-34

但不起作用?有什么想法吗? id是唯一的,只能显示1个索引。

您可以使用它

public func getIndex(id : Int){
    if let index = options.index(where: { $0.components(separatedBy: "-").last == "\(id)" }) {
        print(index, options[index])
    }
}
编辑:代替像这样的硬编码字符串,制作一个
struct
或自定义
class
,这将对您有很大帮助

struct Person { 
    var id: Int
    var name: String
}
现在制作这个结构的数组,然后很容易过滤数组

var options = [Person]()
public func getIndex(id : Int){
    if let index = options.index(where: { $0.id == id }) {
        print(index, options[index])
    }
}

伙计,如果id=34,我的数组有341342343个值?我想这会是个错误。只能是来自getIndex(id:341)@SwiftDeveloper的唯一id,我用
编辑了答案。组件(分隔符:)
从包含检查,现在只显示真实的唯一id,对吗?具有separatedBy@SwiftDeveloper为什么要在对象名称中硬编码对象索引?!感觉是你在制造你现在必须解决的问题@SwiftDeveloper是的为什么这些奇怪的复合参数让你的生活如此艰难?这是一种面向对象的语言。使用自定义结构。