Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以覆盖swift中的查找(序列、元素)功能?_Swift - Fatal编程技术网

是否可以覆盖swift中的查找(序列、元素)功能?

是否可以覆盖swift中的查找(序列、元素)功能?,swift,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

我有一个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")

谢谢您的帮助。

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

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

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

    return nil
}()

正如@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]
}

谢谢Kirsteins。我曾考虑迭代数组,但想知道是否可以重写find()override,因为它不会更改方法的签名。只能重写超类的方法<代码>查找是与任何类型都不关联的独立功能。您可以在@rintaro answer中更改方法的签名。这就是所谓的(方法/函数)重载。谢谢@rintaro,但我在写的时候遇到了一个“找不到成员‘name’”错误:如果让find=find(数组,{$0.name==“对象的名称”{让myFoundObject=array[found]}很好,我没有调用正确的find函数。再次感谢。
if let found = find(array, { $0.name == "name_of_the_object_I_m_looking_for" }) {
    let myFoundObject = array[found]
}