2017-05-29 67 views
0

我有一個數組匹配陣列字符串值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(編號:34) //必須是SHOW約翰 - 34

但不工作?任何想法? id是唯一的,只能顯示1個索引。

+1

你爲什麼用這些奇怪的複合參數讓自己的生活變得如此艱難?這是一種面向對象的語言。使用自定義結構。 – vadian

回答

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

老兄,如果id = 34,我的數組有341,342,343個值?我認爲會出現一個錯誤。只有必須來自哪個獨特的編號從getIndex(編號:341) – SwiftDeveloper

+0

@SwiftDeveloper我編輯答案與'.components(separateBy:)'從包含檢查 –

+0

現在只會顯示TRUE唯一的ID嗎?與分離BY – SwiftDeveloper