首先声明数组
//: Playground - noun: a place where people can play
import UIKit
let nums = [1,2,3,4,5]
let string = ["l","h","j"]
//数组中操作函数 返回值大多是optional 因为系统不知道这个数组是否为空
let num1 =nums.first
let string1 =string.first
//nil
let empty = [Int]()
empty.first
nums.max()
string.max()
//遍历数组 c和java的Style
for index in 0..<nums.count
{
num[index]
}
//swift中拿元素写法
for number in nums
{
number
}
//swift拿元素及其下标写法 使用元组
for(index,value) in string.enumerated()
{
print("\(index) : \(value)")
}
let NUM = [1,2,3,4,5]
//在OC或其他语言中 对于对象不可以直接用这种==对比 它们是比较引用,即对比地址 而基本类型就可以(int,double,float等)
//swift中==是内容的对比,即数据内容
num==NUM //这里值是true
//以下是OC的数组 java也一样 不过如果是自定义类的话 可以重写其对比方法 如equals()方法
NSArray*OCArray =@[@"1",@1];
NSArray*OCArray1 =@[@"1",@1];
NSLog(@"%u",OCArray==OCArray1);
在控制台输出是0 即不相等
以下是数组的增删改操作
//: Playground - noun: a place where people can play
import UIKit
var numO : [Int]? = nil
var num = [1,2,3,4,5]
//增
//这里如果使用感叹号会崩溃 ?就是尝试解包 解包错误就返回nil
numO?.append(6)
//即使是增加一个元素也要包装成数组
num += [7]
num += num[1...2]
//num += num
num.insert(10, at: 2)
//删
//这里并不是optional返回值
numO?.remove(at: 2)
num
num.removeSubrange(1...2)
//改
num[1] = 2
num
// - i: A valid index of the array.
// - n: The distance to offset `i`.
//返回的是下标 非optional
num.index(2, offsetBy: 3)
for _ in 1...2{
print("梁华建")
}
//range值和replace的index值可以不同
num
num[0...2] = [7]
num