码迷,mamicode.com
首页 > 编程语言 > 详细

swift数组

时间:2016-06-04 11:58:45      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

//: Playground - noun: a place where people can play

import UIKit

//------数组----------//
//数组强调的有序,而不是数组中的元素是否重复
//Swift中的数组必须确定里面存储何种类型的数据,且一个数组只能存储相同类型的数据

let devices : [String] = ["iPhone", "iPad", "Mac"]
print(devices)

//1.创建空数组
let array1 = []
let array2 : [Int] = []
var array3: Array<Int> = []
let array4 = [String]() //用构造函数来创建一个空数组

//2.数组元素的类型一定要相同
//let numbers: [String] = ["x", 2.34]
//print(numbers)

//3.创建带默认值的数组
var list = [1,1,2,3,4,5,6]
//swift更安全,如果索引越界,则直接报错
//list[7]

//4.构建子数组
var subList1 = list[2...4]
var subList2 = list[2..<4]

//5.遍历数组
for number in list[2...4] {
    
    print(number)
}
//默认i为常量,如果想在循环体中改变其值,则设置为变量
for var i in list {
    
    i++
    print(i)
}

//6.数组常用的方法
//(1)末尾添加元素
var players  = ["悟空", "悟能", "悟净"]
players.append("唐僧")

let newPlayers = players + ["白龙马"]

players += ["金吒","木吒","哪吒"]

//(2)替换元素
players[1] = "金角大王" //返回替换后的新值
players[2...4] = ["", "", ""]
print(players)

//(3)插入元素:在索引值之前添加数据项
players.insert("银角大王", atIndex: 2)
print(players)

//(4)删除元素
players.removeFirst()
players.removeLast()
players.removeAtIndex(2)
print(players)

//7.数组也是值类型--深copy 在内存中创建一个新的数组,用来保存原数组中所有的元素
//数组中的元素发生深copy还是浅copy取决于数组元素的类型是值类型还是引用类型
var players2 = players
players2.append("白骨精")
print(players)

 

swift数组

标签:

原文地址:http://www.cnblogs.com/foreveriOS/p/5558428.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!