ios - 订阅 self 是什么意思?

标签 ios swift

<分区>

我在 Eureka 项目中遇到了一些奇怪的代码行 here

public subscript(indexPath: NSIndexPath) -> BaseRow {
    return self[indexPath.section][indexPath.row]
}

这让我很困惑。它是如何工作的?

最佳答案

通过documentation

Subscripts

Classes, structures, and enumerations can define subscripts, which are >shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval. For example, you access elements in an Array instance as someArray[index] and elements in a Dictionary instance as someDictionary[key].

You can define multiple subscripts for a single type, and the appropriate >subscript overload to use is selected based on the type of index value you pass to the subscript. Subscripts are not limited to a single dimension, and you can define subscripts with multiple input parameters to suit your custom type’s needs.

•   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"

关于ios - 订阅 self 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35485071/

相关文章:

ios - 代码签名错误 : a valid provisioning profile matching the application's Identifier 'program' could not be found

ios - 没有网络连接时 React Native IOS App 崩溃

ios - 无法在iOS Simulator中将通行证添加到电子钱包,但未记录任何内容

swift - 在 DecodingError 中采用 CustomNSError

ios - 在 Swift 中自定义 AdColony V4VC 弹出菜单

casting - 如何在 "for in"枚举中快速转换元组?

ios - TestFlight- 如何向个别候选人发送测试构建的邀请

ios - 动态创建应用程序图标

ios - 如何访问 PFObject 中的信息?

JSONDecoder 给出不正确的格式