Swift之数组

2020-03-06  本文已影响0人  豌豆_b314

参考文档:
https://developer.apple.com/documentation/swift/array

一、数组的定义


var arr1 = [1,2,3,4]

var arr11:[Int] = [1,2,3,4]

var arr111:Array<Int> = [1,2,3,4]



//空数组

//var arr2 = [] //你这个到底什么类型?无法推断

var arr2:[Int] = []

var arr22 = [Int]()

//生成一个数组,10个元素,每个元素默认都是0

var arr3 = [Int](repeatElement(0,count:10))

print(arr3)

二、基本操作


print(arr3.count)//获取数组长度

print(arr2.isEmpty) //判断是否为空

print(arr1[1])//下标从0开始

print(arr1[1...3])

print(arr1[1...])

print(arr1[1..<3])

print(arr1.first!)//获取数组第一个

print(arr1.last!)

三、数组遍历


//遍历1

for index in 0..<arr1.count{

    print(arr1[index])

}

//遍历2

for number in arr1{

    print(number)

}

四、增删改查

// 增: 1)在末尾  2)在指定位置
var girlFriends = ["刘亦菲","迪丽热巴","杨幂","汤唯"]
girlFriends += ["刘诗诗"]
girlFriends.append("柳岩")
girlFriends.insert("翠花",at:0)

//删除: 1)删除单个  2)删除一片
girlFriends.remove(at:3)
girlFriends.removeSubrange(2..<5)

//改
girlFriends+=["迪丽热巴","杨幂","汤唯"]
girlFriends[0]="红花"
girlFriends[2..<4]=["哈哈"]

//查
print(girlFriends.contains("哈哈"))
print(girlFriends)
上一篇下一篇

猜你喜欢

热点阅读