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

Jus*_*ore 1 generics if-statement iequatable control-flow swift

AMRoute类有两个属性,city1和city2,类型为AMCity类.许多AMRoutes存储在arrayOfRoutes数组中.在创建新路线时,我首先需要确保两个给定城市不存在路线.

我很难翻译这个工作的Obj-C代码:

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,我不能使用'=='运算符来比较像我以前在Obj-C中使用的对象.我在搜索主题时发现的例子向我指出了泛型:

    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
}
Run Code Online (Sandbox Code Playgroud)

我不确定如何在我的案例中加入这个.我不需要比较数组中的AMRoute对象.我需要将存储为AMRoute,city1和city2属性的对象作为AMCity对象进行比较.

Ste*_*erg 5

您可以将swift中的对象与"==="相同的运算符进行比较.