본문 바로가기
Swift/Language Guide

Collection Types - #1/2 : Array

by diosmio 2021. 9. 9.

서문

Swift에는 3개의 메인 Collection type이 있다

- Array : 순서 O

- Dictionary : 순서 X + (요소유일성...?)

- Set : 순서 X + 요소유일성

 

또한, key와 value의 타입을 명확히 해야하고

처음 선언한 타입과 동일한 타입만 요소가 될 수 있다

 

 

 

Mutability of Collections

collection type을 var로 선언하면 요소를 바꿀 수 있다

바꾸지 않을 예정이면 let 선언하여 최적화하자

 

 

Array

Array는 같은 타입의 value들을 순서가 있는 list로 저장한다

 

또한, 같은 value를 가지는 item이 여러개 존재할 수도 있다

 

나중에 Foundation의 NSArray 클래스와 브릿지된다

 

Array Type Shorthand Syntax

정석은 Array<Element>이나 보통 축약 버전인 [Element]를 많이 쓴다

 

 

Creating an Empty Array

코드를 짜다보면 빈 Array를 일단 만들어야 하는 경우가 있다

 

예제로 확인하자

var someInts: [Int] = []
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

위의 경우 []만으로는 someInts의 타입을 추정할 수 없으므로 반드시 [Int]로 타입을 명시해주어야 한다

 

 

Creating an Array with a Default Value

같은 value를 반복하여 구성된 Array를 만들어주는 initializer가 제공된다

 

예제로 확인하자

var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

 

Creating an Array by Adding Two Arrays Together

같은 타입을 value로 가지는 Array들을 합쳐서 만드는 방법도 있다

(+)연산자를 활용한다

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

 

 

Creating an Array with an Array Literal

리터럴로 선언할 수 있다

var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items

당연히 [String]으로 선언해놓고 우변에서 String이 아닌 타입을 쓰면 오류가 발생한다

이 경우 타입은 생략해도 컴파일러가 리터럴을 보고 추론할 수 있다

 

 

 

Accessing and Modifying an Array

가~장 중요한 부분이 등장했다

 

Array의 각 Element로는 메소드/프로퍼티/subscript로 접근할 수 있다

 

Subscript를 쓸 땐 존재하지 않는 Element를 가리킬 경우 런타임 에러를 유발하므로 주의해야 한다

공식 문서에서는 count 프로퍼티를 사용하여 valid 체크하길 권하고 있다

 

[ Meta정보 ] 

● Array size -> Array.count

print("The shopping list contains \(shoppingList.count) items.")
// Prints "The shopping list contains 2 items."

● Array가 비었는지 -> Array.isEmpty

if shoppingList.isEmpty {
    print("The shopping list is empty.")
} else {
    print("The shopping list isn't empty.")
}
// Prints "The shopping list isn't empty."

 

[ 추가 ]

● 끝자리에 Element 추가 -> Array.append( _: ) 혹은 (+=)연산자

shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes

shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items

● 특정 위치에 Element 추가 -> Array.insert( _:, at: )

shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list

[ 제거 ]

● 특정 위치의 Element 제거 -> Array.remove( at: )

- remove 메소드는 반환값을 가진다.

- 지운 Element를 반환

- C언어 배열과 달리 remove를 하면 자동으로 한칸씩 당겨진다

let mapleSyrup = shoppingList.remove(at: 0)
// the item that was at index 0 has just been removed
// shoppingList now contains 6 items, and no Maple Syrup
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string

● 마지막 Element 제거 -> Array.removeLast( )

let apples = shoppingList.removeLast()
// the last item in the array has just been removed
// shoppingList now contains 5 items, and no apples
// the apples constant is now equal to the removed "Apples" string

 

[ 요소 ] 

● index기반 Element 추출 -> Array[n]

var firstItem = shoppingList[0]
// firstItem is equal to "Eggs"

shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"

● 여러 Element 한꺼번에 추출 -> Array[m...n]

shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items

 

[ 루프 

● 각 Element를 하나씩 모두 추출 -> for element in Array

for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas

● (index와 함께) 각 Element를 하나씩 모두 추출 -> for (index, element) in Array.enumerated( )

- enumerated( ) 메소드를 사용하면 각 Element가 index가 더해진 튜플이 된다

for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas

 

 

 

'Swift > Language Guide' 카테고리의 다른 글

Functions - #1/1  (0) 2021.09.12
Type Casting - #1/1  (0) 2021.09.10
Collection Types - #2/2 : Set, Dictionary  (0) 2021.09.10
Strings and Characters - #2/2  (0) 2021.09.06
Strings and Characters - #1/2  (0) 2021.09.06

댓글