简体   繁体   English

在Swift中使用Equatable将对象比较为属性

[英]Comparing objects as properties using Equatable in Swift

AMRoute class has two properties, city1 & city2, of type AMCity class. AMRoute类具有AMCity类类型的两个属性city1和city2。 Numerous AMRoutes are stored in an array, arrayOfRoutes. 许多AMRoutes存储在arrayOfRoutes数组中。 When creating a new route, I first need to ensure no routes exist with two given cities. 创建新路线时,我首先需要确保在两个给定的城市中不存在任何路线。

I am having a hard time translating this working Obj-C code: 我很难翻译此有效的Obj-C代码:

-(void)createRouteFromCity:(AMCity*)city1 toCity:(AMCity*)city2 { -(void)createRouteFromCity:(AMCity *)city1 toCity:(AMCity *)city2 {

 BOOL routeExists = NO; for (AMRoute *route in self.arrayOfRoutes) { if (((route.city1 == city1) && (route.city2 == city2)) || ((route.city2 == city1) && (route.city1 == city2))) { routeExists = YES; } } 

It is my understanding that I cannot use the '==' operator to compare objects like I used to in Obj-C. 据我了解,我无法像在Obj-C中那样使用'=='运算符来比较对象。 The examples I found while searching the topic point me to generics: 我在搜索主题时发现的示例将我指向泛型:

    func createRoute(city1: AMCity, city2: AMCity) {

    var routeExists = false

    findIndex(self.arrayOfRoutes, valueToFind: <#T#>) //i am not sure how to call this?        
    for route:AMRoute in self.arrayOfRoutes {
    println("The city is: \(route.city1.name)")

    }

}

func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
    for (index, value) in enumerate(array) {
        if value == valueToFind {
            return index
        }
    }
    return nil
}

I'm not sure how to incorporate this in my case. 我不确定如何将其纳入我的案例。 I don't need to compare AMRoute objects in the array. 我不需要比较数组中的AMRoute对象。 I need to compare objects stored as properties of AMRoute, city1 & city2 as AMCity objects. 我需要比较存储为AMRoute,city1和city2属性的对象作为AMCity对象。

您可以使用“ ===”相同的运算符快速比较对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM