2017-05-29 76 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