小编Jer*_*hao的帖子

函数和下标之间有什么区别,尤其是下面的代码?

我读了“快速编程语言”,下标让我感到困惑,下面有一个带下标的示例,但是我也可以用一个函数来实现它,那么下标与函数相比到底意味着什么?

以下示例具有相同的输出“ 6 3 x 18”。

struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}

let threeTimesTable = TimesTable(multiplier: 3)

println("6 times 3 is \(threeTimesTable[6])")


struct TimesTable2 {
    let multiplier: Int
    func times (index: Int) -> Int {
        return multiplier * index
    }
}

let threeTimesTable2 = TimesTable2(multiplier: 3)

println("6 times 3 is \(threeTimesTable2.times(6))")
Run Code Online (Sandbox Code Playgroud)

swift

1
推荐指数
1
解决办法
568
查看次数

标签 统计

swift ×1