iOS/Swift

콜렉션 타입(Collection Types) - Array

Brad_Heo 2023. 4. 19. 22:38

Swift에서는 콜렉션 타입으로 Array, Set, Dictionary 세 가지를 지원 합니다.

콜렉션의 변경

Array, set, Dictionary를 변수(var)에 할당하면 이 콜렉션은 변경 가능하고 상수(let)에 할당하면 변경 불가능 합니다.

배열(Array)

배열의 축약형 문법

배열 타입은 Array로 적을 수 있는데 축약형으로 [Element]형태로 사용할 수도 있습니다.

빈 배열의 생성

아래와 같이 Int형 빈 배열을 생성할 수 있습니다.

var someInts = [Int]()
someInts.append(3)
// 배열에 3을 추가 했습니다.
someInts = []
// 배열을 비웠습니다. 배열의 아이템 타입은 그대로 Int로 유지 됩니다.

기본값으로 빈 배열 생성

repeating 메소드와 count 메소드를 이용해 기본 값으로 빈 배열을 생성할 수 있습니다.

var threeDoubles = Array(repeating: 0.0, count: 3)

다른 배열을 추가한 배열의 생성

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles : [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles : [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

리터럴을 이용한 배열의 생성

[value 1, value 2, value 3] 형태를 이용해 배열을 생성할 수 있습니다.

var shoppingList: [String] = ["Eggs", "Milk"]

더 간단하게 선언할 수 있습니다.

var shoppingList = ["Eggs", "Milk"]

배열의 접근 및 변환

배열의 원소 개수 확인

print(shoppingList.count)
// 2

배열의 원수 개수 확인

if shoppingList.isEmpty {
    print("Is empty")
} else {
    print("Is not empty")
}

배열에 원소 추가

shoppingList.append("Four")
// shoopingList.count = 3
shoppingList += ["Baking powder"]
// shoopingList.count = 4
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoopingList.count = 7

배열의 특정 위치에 원소 접근

var firstItem = shoppingList[0]
// firestItem = "Egg"

shoppingList[4...6] = ["Bananas", "Apples"]
// 4, 5, 6번째 인덱스 아이템을 Banana, Apples로 변환
// 즉, 아이템 3개가 2개로 줄었다.

특정 위치에 원소 추가/삭제/접근

shoppingList.insert("Maple Syrup", at: 0)

let mapleSyrup = shoppingList.remove(at: 0)

firstItem = shoppingList[0]
// firstItem: "Six eggs"

let apples = shoppingList.removeLast()

배열의 순회

for-in loop을 이용해 배열을 순회할 수 있습니다.

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

배열의 값과 인덱스가 필요할 때는 enumerated() 메소드를 사용 합니다.