我在Eureka项目here
中遇到了一些奇怪的代码public subscript(indexPath: NSIndexPath) -> BaseRow {
return self[indexPath.section][indexPath.row]
}
它让我很困惑。它是如何工作的?
答案 0 :(得分:2)
将此方法添加到类或结构
public subscript (index: Int) -> Element {
// ...
}
允许您使用自己的类订阅。
实施例
public class Sentence {
private let words: [String]
init(sentence:String) {
self.words = sentence.characters.split(" ").map(String.init)
}
public subscript (index: Int) -> String {
return words[index]
}
}
let sentence = Sentence(sentence: "Hello world")
sentence[0] // "Hello"
// ^ <-- this will call the subscript method
答案 1 :(得分:2)
<强>下标强>
类,结构和枚举可以定义下标,这些是用于访问集合,列表的成员元素的&gt;快捷方式, 或序列。您可以使用下标按索引设置和检索值 无需单独的设置和检索方法。对于 例如,您可以访问Array实例中的元素someArray [index] 和Dictionary实例中的元素为someDictionary [key]。
您可以为单个类型定义多个下标,并根据类型选择要使用的相应&gt;下标重载 传递给下标的索引值。下标不限于a 单维度,您可以定义具有多个输入的下标 参数以满足您的自定义类型的需求。
• struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
println("six times three is \(threeTimesTable[6])")
// prints "six times three is 18"
答案 2 :(得分:1)
所以其他答案定义了一般的下标,但是从帖子的标题来看,我假设你在问什么行
return self[indexPath.section][indexPath.row]
确实
非常简单,它将下标应用于self
,然后将另一个下标应用于结果。这个功能
public subscript(indexPath: NSIndexPath) -> BaseRow {
return self[indexPath.section][indexPath.row]
}
根据其他已定义的下标定义NSIndexSet
上的下标。 section
的{{1}}属性是一个int,您将看到Form类在此扩展中的NSIndexSet
上定义下标:
Int
所以extension Form : MutableCollectionType {
// MARK: MutableCollectionType
public var startIndex: Int { return 0 }
public var endIndex: Int { return kvoWrapper.sections.count }
public subscript (position: Int) -> Section {
get { return kvoWrapper.sections[position] as! Section }
set { kvoWrapper.sections[position] = newValue }
}
}
返回一个self[indexPath.section]
对象,然后由另一个int(Section
)订阅以返回indexPath.row
(请参阅下面的BaseRow
Int
上的}下标。