Swift的基本知识(2)— 数组与字典

Swift数组

定义数组:

var myArray = [Int]()    

var myArray1 = [Int](repeating: 0, count: 10)  索引从 0 开始,即索引 0 对应第一个元素,索引 1 对应第二个元素,以此类推。

数组的添加:

myArray.append(12)

myArray += [13]

myArray.append(14)

数组的修改:

myArray[2] = 15

遍历数组:

for x in myArray {

    print(x)

}

for x in myArray1 {

    print(x)

}

遍历数组和对应的索引:

for x in myArray.enumerated() {

    print(x.offset,x.element)

}

合并数组:

可以使用加法操作符(+)来合并两种已存在的相同类型数组。

var intsA = [Int](repeating: 2, count:2)

var intsB = [Int](repeating: 1, count:3)

var intsC = intsA + intsB

for item in intsC {

    print(item)

}

count属性以及isEmpty属性:

myArray.count      指myArray数组的元素个数

myArray.isEmpty   指对myArray是否为空的判断,返回值为true/false

Swift字典

创建一个空字典,键的类型为 Int,值的类型为 String 的简单语法:

var someDict = [Int: String]()

创建一个字典的实例:

var someDict:[Int:String] = [1:"One", 2:"Two", 3:”Three"]

通过key值访问数组的值:

var someVar = someDict[1]   //值为:One

可以使用 updateValue(forKey:) 增加或更新字典的内容。如果 key 不存在,则添加值,如果存在则修改 key 对应的值。updateValue(_:forKey:)方法返回Optional值。实例如下:

var oldVal = someDict.updateValue("One 新的值", forKey: 1)

可以通过指定的 key 来修改字典的值

someDict[1] = "One 新的值”

我们可以使用 removeValueForKey() 方法来移除字典 key-value 对。如果 key 存在该方法返回移除的值,如果不存在返回 nil

var removedValue = someDict.removeValue(forKey: 2)

可以通过指定键的值为 nil 来移除 key-value(键-值)对

someDict[2] = nil

遍历字典:

import Cocoa

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

for x in someDict{

  print(x.key,x.value)

}

count属性以及isEmpty属性:

someDict.count      指someDict字典的键值对的个数

someDict.isEmpty   指对someDict是否为空的判断,返回值为true/false

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三岁牧羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值