源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Swift 3.0基础学习之下标

  • 时间:2020-04-09 22:58 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Swift 3.0基础学习之下标
[b]前言[/b] 类,结构体和枚举都可以定义下标,使用下标可以快速访问集合,列表或者序列的数据成员元素。可以使用[code]someArray[index][/code]来访问Array, 使用[code]someDictionary[key][/code]来访问Dictionary。 [b]一个类型可以定义多个下标。[/b] [b]定义一个get set的下标:[/b]
subscript(index: Int) -> Int {
 get {
  // return an appropriate subscript value here
 }
 set(newValue) {
  // perform a suitable setting action here
 }
}
[b]定义一个read-only的下标[/b]
subscript(index: Int) -> Int {
 // return an appropriate subscript value here
}
[b]例子:[/b]
struct TimesTable {
 let multiplier: Int
 subscript(index: Int) -> Int {
  return multiplier * index
 }
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// Prints "six times three is 18"
[b]还可以使用多个下标, 任何类型,除了in-out类型的参数[/b]
struct Matrix {
 let rows: Int, columns: Int
 var grid: [Double]
 init(rows: Int, columns: Int) {
  self.rows = rows
  self.columns = columns
  grid = Array(repeating: 0.0, count: rows * columns)
 }
 func indexIsValid(row: Int, column: Int) -> Bool {
  return row >= 0 && row < rows && column >= 0 && column < columns
 }
 subscript(row: Int, column: Int) -> Double {
  get {
   assert(indexIsValid(row: row, column: column), "Index out of range")
   return grid[(row * columns) + column]
  }
  set {
   assert(indexIsValid(row: row, column: column), "Index out of range")
   grid[(row * columns) + column] = newValue
  }
 }
}
参考翻译英语原文: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html#//apple_ref/doc/uid/TP40014097-CH16-ID305 [b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者使用Swift能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部