# Swift陣列

Swift 4陣列用於儲存相同型別的有序值列表。 Swift 4進行了嚴格的檢查，不允許在陣列中輸入錯誤的型別。

#### 建立陣列

``````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]
``````

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

var someVar = someInts[0]
print( "Value of first element is \(someVar)" )
print( "Value of second element is \(someInts[1])" )
print( "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
``````

#### 修改陣列

``````var someInts = [Int]()

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

var someVar = someInts[0]

print( "Value of first element is \(someVar)" )
print( "Value of second element is \(someInts[1])" )
print( "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
``````

``````var someInts = [Int]()

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

// Modify last element
someInts[2] = 50

var someVar = someInts[0]

print( "Value of first element is \(someVar)" )
print( "Value of second element is \(someInts[1])" )
print( "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
``````

#### 疊代陣列

``````var someStrs = [String]()

someStrs.append("Apple")
someStrs.append("Amazon")
for item in someStrs {
print(item)
}
``````

``````Apple
Amazon
``````

``````var someStrs = [String]()

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

for (index, item) in someStrs.enumerated() {
print("Value at index = \(index) is \(item)")
}
``````

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

#### 新增兩個陣列

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

var intsC = intsA + intsB
for item in intsC {
print(item)
}
``````

``````2
2
1
1
1
``````

#### count屬性

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

var intsC = intsA + intsB

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

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

#### empty屬性

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

print("intsA.isEmpty = \(intsA.isEmpty)")
print("intsB.isEmpty = \(intsB.isEmpty)")
print("intsC.isEmpty = \(intsC.isEmpty)")
``````

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