是否有可能在swift中覆盖find(sequence,element)函数?

时间:2015-02-10 11:29:08

标签: swift

我有一个MyObject数组,我的对象是这样的:

class MyObject: Equatable {
   var name: String?
   var age: Int?

   init(name: String, age: Int) {
      self.name = name
      self.age = age
   }
}

func ==(first: MyObject, second: MyObject) -> Bool {
    return first.name == second.name
}

假设我的数组是:

var array: [MyObject]

有没有办法像这样使用find(sequence,element)函数? :

var myFoundObject = find(array, "name_of_the_object_I_m_looking_for")

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

find函数返回集合中对象的索引,而不是对象。

您必须迭代ovre数组才能找到符合您条件的对象,例如:

var myObject: MyObject? = {
    for object in array {
        if "name_of_the_object_I_m_looking_for" == object.name {
            return object
        }
    }

    return nil
}()

答案 1 :(得分:1)

正如@Kirsteins所提到的,find返回索引。

您可以轻松实现自己的find接受测试功能,例如filter

func find<C:CollectionType, U where C.Generator.Element == U>(domain:C, isValue:U -> Bool) -> C.Index? {
    for idx in indices(domain) {
        if isValue(domain[idx]) {
            return idx
        }
    }
    return nil
}

// usage
let array = ["foo", "bar", "baz"]
if let found = find(array, { $0.hasSuffix("az") }) {
    let obj = array[found]
}

使用此功能,您可以:

if let found = find(array, { $0.name == "name_of_the_object_I_m_looking_for" }) {
    let myFoundObject = array[found]
}