[Swift] Collection Types - 1. Array

Byunghoon Lee·2021년 7월 12일
0

iOS

목록 보기
2/11
post-thumbnail

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

기본 문법에서도 다뤘지만, 배열, set, dictionary를 변수(var)에 할당하면 변경가능하고, 상수(let)에 할당 하면 변경이 불가능 합니다.

배열 (Array)

빈 배열의 생성

빈 배열의 경우 아래와 같이 표기할 수 있습니다.

var emptyArr = [Int]() 
or
var emptyArr : [Int] = []
print("someInts is of type [Int] with \(emptyArr.count) items.")

// someInts is of type [Int] with 0 items.

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

[value 1, value 2, value 3]의 형태로 배열을 생성할 수 있습니다.

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

배열의 접근 및 수정

아래의 방법으로 접근 및 수정을 할수 있습니다.

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

배열의 갯수 파악 (읽기만 가능)

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

Boolean(참,거짓)으로 빈 배열인지 파악

if shoppingList.isEmpty {
    print("The shopping list is empty.")
} else {
    print("The shopping list isn't empty.")
}
// "The shopping list isn't empty." 
// shoppingList 의 배열엔 2개의 아이템이 있기 때문.

기존 배열에 새로운 아이템 추가 (append, += 메서드사용)

shoppingList.append("Flour")
print(shoppingList) // ["Eggs", "Milk", "Flour"]
		    or
shoppingList += ["Cheese"]
print(shoppingList) // ["Eggs", "Milk", "Flour", "Cheese"]

배열에서 아이템 추출 (가져오기)

var firstItem = shoppingList[0]
// shoppingList의 첫번째 인덱스 [0]는 ["Eggs"]
print(firstItem) // Eggs

기존 배열에 특정 아이템 변경

shoppingList[0] = "Six eggs"
print(shoppingList) // ["Six eggs", "Milk", "Flour", "Cheese"]
		     or
shoppingList[3...] = ["Bananas", "Apples"]
print(shoopingList) // ["Six eggs", "Milk", "Flour", "Bananas", "Apples"]
// 인덱스 3번째부터 ["Bananas", "Apples"] 배열로 변경. 따라서 3번째 인덱스였던 "Cheese"가 없어짐

아이템을 특정 위치에 추가/삭제

// 추가
shoppingList.insert("Maple Syrup", at: 0)
print(shoppingList) // ["Maple Syrup", "Six eggs", "Milk", "Flour", "Bananas", "Apples"] 
// at:추가하고 싶은 아이템 위치(인덱스)
// 삭제
let removeMapleSyrup = shoppingList.remove(at:0)
print(shoppingList) // ["Six eggs", "Milk", "Flour", "Bananas", "Apples"]
// 마지막 아이템 삭제
let removeApples = shoppingList.removeLast()
print(shoppingList) // ["Six eggs", "Milk", "Flour", "Bananas"]

배열 반복

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

반복문에서 index가 필요할 경우. enumerated() 메서드 사용

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

참고 : Swift 공식문서

profile
Never never never give up!

0개의 댓글