github上swift源码
https://github.com/apple/swift
有兴趣的同学可以参看Array相关的源码
ContiguousArray源码
下面是数组一些最基本的运用:
//声明一个不可修改的数组
let nums = [1,2,3]
let nums = [Int](repeating:0, count:5)
//声明一个可以修改的数组
var nums = [3,1,2]
//增加一个元素
nums.append(4)
//对原数组进行升序排序
nums.sort()
//对原数组进行降序排序
nums.sort(by: >)
//将原数组除最后一个外的所有元素赋值给另一个数组
let anotherNums = Array(nums[0..<nums.count-1])
用数组实现栈的示例代码
class Stack{
var stack:[AnyObject]
var isEmpty:Bool{return stack.isEmpty}
var peek:AnyObject?{return stack.last}
init() {
stack = [AnyObject]()
}
func push(object:AnyObject) {
stack.append(object)
}
func pop() -> AnyObject? {
if(!isEmpty) {
return stack.removeLast()
} else {
return nil;
}
}
}
栈调用方式
let a = Stack.init();
a.push(object: 5 as AnyObject)
a.push(object: 3 as AnyObject)
a.push(object: 2 as AnyObject)
a.pop()