Swift教程之NSArray

前端之家收集整理的这篇文章主要介绍了Swift教程之NSArray前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//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)
原文链接:https://www.f2er.com/swift/326696.html

猜你在找的Swift相关文章