加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

10.7 Swift中subscripts具体实现

发布时间:2020-12-14 06:31:52 所属栏目:百科 来源:网络整理
导读:let array = [ 1 , 2 , 3 , 4 , 5 ] // 我们可以写成这个样子 let array1: [ Int ] = [ 1 , 3 ] let array2: Array Int = [ 1 , 3 ] print (array[ 1 ]) // 实例对象 [ 索引 ] subscripts let dict = [ "1" : 1 ] // key:value,key hash let dict1: Dictiona

let array = [1,2,3,4,5]

// 我们可以写成这个样子

let array1: [Int] = [1,3]

let array2:Array<Int> = [1,3]

print(array[1]) // 实例对象 [索引] subscripts

let dict = ["1" :1] // key:value,key hash

let dict1:Dictionary<String,Int> = ["1" :1]

print(dict["1"])

/**

比如我也想构造一个结构体或者类

可以像以上这样通过实例下标的方式访问,

Swift是可以做到的。

按住 command键单击点击进入我们可以看到

public subscript(index: Int) -> Element // array

array.subscript(index)

public subscript(key: Key) -> Value? // dict

dict.subscript(key)

*/


/**

subscripts具体实现

*/

struct Student {

let name:String = ""

var math:Int = 0

var chinese:Int = 0

var english:Int = 0

func scoreOf(course:String) -> Int? {

switch course {

case"math":

returnmath

case"chinese":

returnchinese

case"english":

returnenglish

default:

returnnil

}

}

// 自定义的实现该结构体下标访问

subscript (course:String) -> Int? {

get {

switch course {

case"math":

returnmath

case"chinese":

returnchinese

case"english":

returnenglish

default:

returnnil

}

}

set {

switch course {

case"math":

returnmath = newValue!

case"chinese":

returnchinese = newValue!

case"english":

returnenglish = newValue!

default:

// return nil

print("key wrong")

}

}

}

}

var xiaoli =Student.init(math:98,chinese: 97,english:100)

print(xiaoli.scoreOf(course:"math"))

// Optional(98)

/**

那么我们如何能够像数组或者字典一样用这种下标的访问方式

xiaoli["math"]

*/

print(xiaoli["math"])

// Optional(98)

xiaoli["math"] =99

print(xiaoli["math"])


/**

subscript (course: String) -> Int?

参数的类型和参数的个数有没有要求,以及返回值类型

它的参数可以是任意的,返回值类型也可以是任意的,

那么参数的个数呢,其实可以做的更复杂一些,比如说下标里面不止一个索引

*/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读