2015-09-05 50 views
5

所以我目前使用的Xcode 7測試一個項目轉換爲斯威夫特2,和我目前得到的錯誤:無法下標類型爲「[NSIndexPath]」的值與int類型

Cannot subscript a value of type '[NSIndexPath]?' with a type 'Int'

爲下面的代碼靈:

let indexPath = indexPaths[0] as! NSIndexPath 

試圖當用戶選擇使用prepareForSegue方法在UICollectionView小區將數據傳遞到一個視圖控制器時。

這裏是完整的prepareForSegue方法。我不確定這是否是Swift 2錯誤,但在使用Swift 1.1 for iOS 8.4時可以正常工作。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 

    if segue.identifier == "details" { 
    let vc = segue.destinationViewController as! DetailsViewController 

    let indexPaths = self.collectionView.indexPathsForSelectedItems() 
    let indexPath = indexPaths[0] as! NSIndexPath 

    let selectedItem = items[indexPath.row] 

    vc.selectedItem = selectedItem 

    } 
} 
+1

嘗試做'let indexPaths = self.collectionView.indexPathsForSelectedItems()as! [NSIndexPath]' –

+0

@TheBeanstalk是啊,這似乎現在做的伎倆,仍然轉換代碼,無法運行atm。 'let indexPaths = self.collectionView.indexPathsForSelectedItems()as [NSIndexPath]!' – RileyDev

+0

如果您單獨保留'indexPaths'這行,而將'let indexPath = indexPaths![0]改爲! NSIndexPath' –

回答

1

在iOS8上的SDK,indexPathsForSelectedItems聲明爲:

func indexPathsForSelectedItems() -> [AnyObject] // returns nil or an array of selected index paths 

這是在SDK中的錯誤,因爲indexPathsForSelectedItems()回報nil在沒有選擇的項目。

在iOS9 SDK,其被聲明爲:

public func indexPathsForSelectedItems() -> [NSIndexPath]? 
這裏

  • 2差異的錯誤是固定的,並且返回Optional

  • 返回NSIndexPath代替AnyObject陣列因爲目的-C支持簡單的泛型。

所以,

  • 你必須解開它。
  • 你並不需要將它們轉換爲NSIndexPath

嘗試:

let indexPaths = self.collectionView.indexPathsForSelectedItems()! 
let indexPath = indexPaths[0] 
2

首先,你應該解開陣列然後用它所以這段代碼應該工作:

let indexPath = indexPaths?[0] as! NSIndexPath 

通過的方式,避免使用!打開有可能爲零的變量或最終的應用程序將面臨運行時崩潰。

0

您需要展開數組,而不是強制展開!如果讓我們確保你沒有展開nil,可能會更安全

if let indexPaths = self.collectionView.indexPathsForSelectedItems() where indexPaths.count > 0{ 
    let indexPath = indexPaths[0] 
} 
相關問題