![](/img/trans.png)
[英]Match a string to a value in an array and return the id of that value in JavaScript
[英]Match array string value inside id with index in Swift 3
我有一個數組
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) //必須顯示約翰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])
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.