找到阵列的位置

时间:2016-01-14 10:46:22

标签: xcode swift swift2

我使用此函数查找标题中数组中的哪个位置,我想知道是否可以以更好/更快的方式执行此操作。

func findId(title:String){
        var id = 0
        for restaurant in restaurantObjects{
            if (restaurant.name == title){

                self.idClicked = id
            }
            else{
                id++
            }
        }        
    }

2 个答案:

答案 0 :(得分:0)

struct Restaurant {
    let name : String
    init(_ name: String) {
        self.name = name
    }
}

let restaurantObjects : [Restaurant] = [Restaurant("foo"), Restaurant("foofoo"), Restaurant("bar"), Restaurant("foo")]
let title = "bar"
if let pos = restaurantObjects.indexOf({ $0.name == title }) {
    print("Found \(title) at index \(pos)") // Found bar at index 2
}

或者,为Restaurant类型的元素创建数组扩展,这样您就可以在.findFirstId(title: String)个对象的数组上调用Restaurant

struct Restaurant {
    var name : String
    init(_ name: String) {
        self.name = name
    }
}

protocol RestaurantObject {
    var name : String { get }
}
extension Restaurant : RestaurantObject {}

extension Array where Element : RestaurantObject {
    func findFirstId(title: String) -> Int? {
        return self.indexOf { $0.name == title }
    }
}

/* Example */
let restaurantObjects : [Restaurant] = [Restaurant("foo"), Restaurant("foofoo"), Restaurant("bar"), Restaurant("foo")]
let title = "bar"

restaurantObjects.findFirstId(title) // 2

答案 1 :(得分:0)

该函数返回一个可选的Int,如果无法找到索引,则为nil

func findId(title:String) -> Int? {
  return restaurantObjects.indexOf{ $0.name == title}
}