Swift 3.0下标 Swift 3.0基础学习之下标

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Swift 3.0下标 Swift 3.0基础学习之下标

Mellong   2021-03-24 我要评论
想了解Swift 3.0基础学习之下标的相关内容吗,Mellong在本文为您仔细讲解Swift 3.0下标的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:swift,下标,swift,下标用法,swift,3.0,下面大家一起来学习吧。

前言

类,结构体和枚举都可以定义下标,使用下标可以快速访问集合,列表或者序列的数据成员元素。可以使用someArray[index]来访问Array, 使用someDictionary[key]来访问Dictionary。

一个类型可以定义多个下标。

定义一个get set的下标:

subscript(index: Int) -> Int {
 get {
  // return an appropriate subscript value here
 }
 set(newValue) {
  // perform a suitable setting action here
 }
}

定义一个read-only的下标

subscript(index: Int) -> Int {
 // return an appropriate subscript value here
}

例子:

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"

还可以使用多个下标, 任何类型,除了in-out类型的参数

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者使用Swift能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们