# Swift數組

Swift 數組用於存儲相同類型的值的順序列表。Swift 要嚴格檢查，它不允許錯誤地在數組中存放了錯誤的類型。

## 創建數組

var someArray = [SomeType]()

var someArray = [SomeType](count: NumbeOfElements, repeatedValue: InitialValue)

var someInts = [Int](count: 3, repeatedValue: 0)

var someInts:[Int] = [10, 20, 30]

## 訪問數組

var someVar = someArray[index]

import Cocoa

var someInts = [Int](count: 3, repeatedValue: 10)

var someVar = someInts[0]

println( "Value of first element is \(someVar)" )
println( "Value of second element is \(someInts[1])" )
println( "Value of third element is \(someInts[2])" )

Value of first element is 10
Value of second element is 10
Value of third element is 10

## 修改數組

import Cocoa

var someInts = [Int]()

someInts.append(20)
someInts.append(30)
someInts += [40]

var someVar = someInts[0]

println( "Value of first element is \(someVar)" )
println( "Value of second element is \(someInts[1])" )
println( "Value of third element is \(someInts[2])" )

Value of first element is 20
Value of second element is 30
Value of third element is 40

import Cocoa

var someInts = [Int]()

someInts.append(20)
someInts.append(30)
someInts += [40]

// Modify last element
someInts[2] = 50

var someVar = someInts[0]

println( "Value of first element is \(someVar)" )
println( "Value of second element is \(someInts[1])" )
println( "Value of third element is \(someInts[2])" )

Value of first element is 20
Value of second element is 30
Value of third element is 50

## 迭代/遍歷數組

import Cocoa

var someStrs = [String]()

someStrs.append("Apple")
someStrs.append("Amazon")

for item in someStrs {
println(item)
}

Apple
Amazon

import Cocoa

var someStrs = [String]()

someStrs.append("Apple")
someStrs.append("Amazon")

for (index, item) in enumerate(someStrs) {
println("Value at index = \(index) is \(item)")
}

Value at index = 0 is Apple
Value at index = 1 is Amazon
Value at index = 2 is Google

## 兩個數組相加

import Cocoa

var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)

var intsC = intsA + intsB

for item in intsC {
println(item)
}

2
2
1
1
1

## count 屬性

import Cocoa

var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)

var intsC = intsA + intsB

println("Total items in intsA = \(intsA.count)")
println("Total items in intsB = \(intsB.count)")
println("Total items in intsC = \(intsC.count)")

Total items in intsA = 2
Total items in intsB = 3
Total items in intsC = 5

## 空屬性

import Cocoa

var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = [Int]()

println("intsA.isEmpty = \(intsA.isEmpty)")
println("intsB.isEmpty = \(intsB.isEmpty)")
println("intsC.isEmpty = \(intsC.isEmpty)")

intsA.isEmpty = false
intsB.isEmpty = false
intsC.isEmpty = true