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

标签 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("\(options[index])"). 
        }
    }

我想用我的函数获取选定的索引;

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

但是不起作用?任何想法? id 是唯一的只能显示 1 个索引。

最佳答案

您可以使用 index(where:)为此。

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])
    }
}

关于arrays - 将 id 内的数组字符串值与 Swift 3 中的索引匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44241163/

相关文章:

php - 将多个表单输入组合成键对值数组并为值添加维度

ios - CIFilter 不工作

ios - NavigationBar 在动画期间改变他的颜色

ios - 在注册 Firebase 之前检查用户名

ios - 使用 constraintEqualToAnchor() 时如何在设置自动布局约束后更改它们?

ios - 配置ios应用程序: Programaticall configuration of ios apps for social login rather than using info. plist

python - numpy 从索引列表创建 3D 数组

java - 将数据从扫描仪写入阵列

arrays - 如何在我的 UI 测试中从 XCUIApplication 访问 NSApplicationDelegate

在C中创建字符串