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

Swift教程之NSArray

发布时间:2020-12-14 02:02:41 所属栏目:百科 来源:网络整理
导读://MARK:-------数组------------------/* 数组与字典 使用[]操作符声明数组(array)和字典(dictionary)*///数组//Demo1: //声明空数组//let emptyArray1: Array = []//var emptyArray2 = Int[]()let emptyArray1 = []var emptyArray2 = [Int]()let emptyA
//MARK:-------数组------------------
/*
    数组与字典
    使用[]操作符声明数组(array)和字典(dictionary)
*/
//数组
//Demo1: //声明空数组
//let emptyArray1: Array = []
//var emptyArray2 = Int[]()
let emptyArray1 = []
var emptyArray2 = [Int]()
let emptyArray3: Array<String> = []

//Demo2:
var shoppingList = ["芒果","橘子","水","葡萄","香蕉"]
//-------------增加-------------
//数组增加元素
shoppingList.append("苹果")
print(shoppingList)
//等价于
//shoppingList += ["柚子"]
//print(shoppingList)

shoppingList += ["西瓜","木瓜"]
print(shoppingList)
//数组插入元素
shoppingList.insert("苹果",atIndex: 2)
print(shoppingList)

//----------------------删除-------------
shoppingList.removeLast()
print(shoppingList)
//需要index < count
shoppingList.removeAtIndex(4)
print(shoppingList)

//shoppingList.removeAll()
//print(shoppingList)

//--------------修改-----------
//修改第一个元素的值
shoppingList[0] = "哈密瓜"
print(shoppingList)
//把下标为4、5、6、7的元素替换成后面的"Bananas","Apples", 值变了,count减少了
shoppingList[1...4] = ["Bananas","Apples"]
print(shoppingList)
//---------查询---------
//常用方法
//数组的个数
print(shoppingList.count)
//数组的容量,值为大于count的 最小的2的n次方的数,比如2、4、8、16
print(shoppingList.capacity)
//判断是否为空
print(shoppingList.isEmpty)


//-----------数组遍历----------
for item in shoppingList
{
    print(item)
}
//数组元素的下标和值
for (index,value) in shoppingList.enumerate()
{
    print("Item (index + 1): (value)")
}


//Demo3:
//----------数组与数组相加---------
var threeDoubles = [Double](count: 3,repeatedValue: 0.0)       //[0.0,0.0,0.0]
print(threeDoubles)

var anotherThreeDoubles = Array(count: 3,repeatedValue: 2.5)   //[2.5,2.5,2.5]
print(anotherThreeDoubles)

var sixDoubles = threeDoubles + anotherThreeDoubles             //[0.0,2.5]
print(sixDoubles)

(编辑:李大同)

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

    推荐文章
      热点阅读