2017-06-29 36 views
0

我有一個名爲array的對象數組,其類型爲votes。在數組的對象中有一個叫做nameSubject的字段,它是一個字符串。 我怎樣才能傳遞我的數組和字符串,我想比較主題的名稱?這是我的函數:二進制搜索:錯誤傳遞數組

static func binarySearch(inputArr: [votes], searchItem: String)->Int?{ 
    var lowerIndex = 0; 
    var upperIndex = inputArr.count - 1 

    while (true) { 
     var currentIndex = (lowerIndex + upperIndex)/2 
     if(inputArr[currentIndex] == searchItem) { 
      return currentIndex 
     } else if (lowerIndex > upperIndex) { 
      return nil 
     } else { 
      if (inputArr[currentIndex] > searchItem) { 
       upperIndex = currentIndex - 1 
      } else { 
       lowerIndex = currentIndex + 1 
      } 
     } 
    } 
} 

的錯誤是在第一和第二if和這樣說:二元運算符「==」不能應用於類型的操作數「票」和「串」」

+0

你想在第二個else語句中做什麼? –

+0

如果你經常這樣做,你最好把'nameSubject'字典映射到'votes'對象 – Alexander

+1

另外,Swift的約定是擁有UpperCamelCase,單數命名類型,比如'Vote' – Alexander

回答

0

你應該與對象的nameSubject字符串,而不是對象本身的字符串比較

所以,你應該做的比較是:

inputArr[currentIndex].nameSubject == searchItem 

雖然這對你之後的比較沒有幫助。我不知道你想與評估哪些屬性「>」

1

這是我怎麼會這樣寫:

// Precondition: the array is sorted by ascending elements 
extension Array where Element: Comparable { 
    func binarySearchForIndex(of desiredElement: Element) -> Int? { 
     return binarySearchForIndex(of: desiredElement, by: {$0}) 
    } 
} 

// Precondition: the array is sorted by ascending values of the picker closure. 
extension Array { 
    func binarySearchForIndex<T>(
     of desiredElement: T, 
     by picker: (Element) -> T 
    ) -> Int? 
    where T: Comparable { 
     var lowerIndex = 0; 
     var upperIndex = self.count - 1 

     while (true) { 
      let currentIndex = (lowerIndex + upperIndex)/2 
      let item = picker(self[currentIndex]) 

      if item == desiredElement { return currentIndex } 
      else if lowerIndex > upperIndex { return nil } 
      else { 
       if (item > desiredElement) { 
        upperIndex = currentIndex - 1 
       } else { 
        lowerIndex = currentIndex + 1 
       } 
      } 
     } 
    } 
} 

的第一個擴展可以讓你在Comparable的任何Array做二進制搜索項目直接。

第二個擴展允許您對任何Array項目進行二分搜索,提供一個閉包,它指定要搜索哪個元素的屬性。你可以這樣做:

let indexOfBobsVote = votes 
    .sorted{ $0.nameSubject < $0.nameSubject} 
    .binarySearchForIndex(of: "bob", by: { $0.nameSubject })