我有一个数组
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/