使用自定义初始化程序时,为什么属性`var row:Int`和`var section:Int`的`IndexPath`会崩溃?

时间:2017-10-08 14:38:49

标签: swift nsindexpath

有必要将属性subrow: Int添加到IndexPath。为什么属性row: Intsection: Int会崩溃?

import UIKit 

extension IndexPath {
    init(subrow: Int, row: Int, section: Int) {
        self.init(indexes: [section, row, subrow])
    }
    var subrow: Int {
        get { return self[2] }
        set { return self[2] = newValue }
    }
}

let ip = IndexPath(subrow: 0, row: 1, section: 2)
print(ip.subrow == 0) // OK
print(ip.row == 1) // Crash!
print(ip.section == 2) // Crash!

1 个答案:

答案 0 :(得分:1)

属性rowsection在扩展程序中定义 在UIKit框架中IndexPath。他们是"方便" 访问器,用于表视图或集合视图。

从API文档中可以看出它们只能用于索引路径 完全两个元素:

extension IndexPath {

    /// Initialize for use with `UITableView` or `UICollectionView`.
    public init(row: Int, section: Int)

    /// The section of this index path, when used with `UITableView`.
    ///
    /// - precondition: The index path must have exactly two elements.
    public var section: Int

    /// The row of this index path, when used with `UITableView`.
    ///
    /// - precondition: The index path must have exactly two elements.
    public var row: Int
}

另请参阅UIKit_FoundationExtensions.swift.gyb的源代码。

您可以改用下标方法:

let ip = IndexPath(subrow: 0, row: 1, section: 2)

print(ip[0]) // 2
print(ip[1]) // 1
print(ip[2]) // 0