簡體   English   中英

[AnyObject]數組的swift indexOf

[英]swift indexOf for [AnyObject] array

試圖獲取數組的索引( [AnyObject] )。 我錯過了什么部分?

extension PageViewController : UIPageViewControllerDelegate {
      func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [AnyObject]) {
        let controller: AnyObject? = pendingViewControllers.first as AnyObject?
        self.nextIndex = self.viewControllers.indexOf(controller) as Int?
      }
    }

我嘗試過使用Swift 1.2這種方法:

func indexOf<U: Equatable>(object: U) -> Int? {
    for (idx, objectToCompare) in enumerate(self) {
      if let to = objectToCompare as? U {
        if object == to {
          return idx
        }
      }
    }
    return nil
  }

輸入'AnyObject?'不符合協議'Equatable' 無法分配“Int?”類型的不可變值

我們需要將我們正在測試的對象轉換為UIViewController ,因為我們知道controllers數組正在保存UIViewController (我們知道UIViewController符合Equatable

extension PageViewController : UIPageViewControllerDelegate {
    func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [AnyObject]) {
        if let controller = pendingViewControllers.first as? UIViewController {
            self.nextIndex = self.viewControllers.indexOf(controller)
        }
    }
}

錯誤背后的邏輯是,為了讓indexOf方法比較傳入的對象,它必須使用==運算符對它們進行比較。 Equatable協議指定該類已實現此函數,因此這是indexOf要求其參數符合的內容。

Objective-C沒有相同的要求,但實際的Objective-C實現最終意味着使用isEqual:方法( NSObject ,因此所有Objective-C類實現)將參數與數組中的對象進行比較。

您必須將viewController屬性強制轉換為Array對象:

if let controllers = self.viewControllers as? [UIViewController] {
    self.nextIndex = controllers.indexOf(controller)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM