0Pricing
Swift Academy · 강의

컬렉션

컬렉션

컬렉션은(는) CoddyKit의 무료 Swift Academy 강의입니다. 이것은 1개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Swift Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Swift Academy 강의에는 총 1개의 강의가 포함되어 있습니다.

소개

안녕하세요.

이 레슨에서는 Swift에서 가장 중요한 주제 중 하나인 컬렉션 유형에 대해 알아보겠습니다.

그럼 시작해 보겠습니다.

Swift에는 3가지 컬렉션 유형이 있습니다.

배열 → 순서가 있는 컬렉션 유형입니다.

집합 → 순서가 없고 고유한 값을 갖는 컬렉션 유형입니다.

딕셔너리 → 순서가 없으며 키-값 쌍으로 구성된 컬렉션 유형입니다.

가변 - 불변

컬렉션 유형이 불변인지 가변인지는 정의 방식에 따라 결정됩니다.

let 문으로 정의하면 불변이 되고, var로 정의하면 가변이 됩니다.

정의한 값이 이후에 변경되지 않는다면 let을 사용하면 컴파일러가 더 최적화된 방식으로 실행할 수 있어 성능상 이점이 있습니다.

배열

배열

배열은 데이터를 순서대로 유지하는 데 사용하는 컬렉션 유형입니다. Swift 3 버전부터는 배열의 모든 요소가 같은 유형일 필요가 없습니다.

간단한 배열 정의의 구문은 아래 예시에 나와 있습니다.

// Let's create an empty array.
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

기본값으로 배열 만들기

기본값으로 배열 만들기

경우에 따라 기본값과 특정 크기를 가진 배열을 만들고 싶을 수 있습니다. 이를 위해 배열 생성자에 두 개의 인수를 전달해야 합니다.

이 인수는 기본값이 무엇인지와 배열에 몇 개의 요소가 포함될지를 지정합니다.

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

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

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

배열 리터럴을 사용하여 배열 생성하기

배열 리터럴을 사용하여 배열 생성하기

이전 예시에서는 빈 배열을 만드는 방법을 배웠습니다. 하지만 경우에 따라 배열 리터럴을 사용하여 배열을 만들고 싶을 수 있습니다.

예시를 통해 사용 방법을 알아보겠습니다.

/*
We have defined a variable named catList, 
and with the [String] statement we specified 
that its type is an Array containing String elements.
*/
var catList: [String] = ["Garfield", "Tom"]
print(catList)
/*
It will understand that the array is an Array containing
String statements, since we assign a value that 
defines the variable. (Swift type inference)
*/
var shoppingList = ["Eggs", "Milk"]
print(shoppingList)

배열 값에 접근하기

배열 값에 접근하기

순서가 있는 컬렉션에서 특정 인덱스의 요소에 접근하려면 다음 구문으로 호출하면 됩니다.

myArray [index]

예시를 살펴보겠습니다.

// We have defined an array with 3 elements of type Int.
var numbers:[Int] = [1, 5, 21]

// Arrays start from Index 0. For example, in order to reach the value 5, which is the 2nd element, we need to access the 1st index.
var a = numbers[1]
print( "Value of numbers at index 1 is \(a)" )

배열에 새 요소 추가하기

배열에 새 요소 추가하기

배열에 새 항목을 추가할 수 있습니다. 

아래 예시에서는 catList라는 배열을 정의합니다. 그런 다음 append 메서드를 사용하여 이 배열에 새 항목을 추가합니다. 

// The Array named catList was defined with 1 initial element.
var catList = ["Tom"]


/*
We are adding a new item with a Garfield 
value using the append method.
*/
catList.append("Garfield")
// Our array will now have 2 elements.


/*
With the + = operator, we can do the 
work that the append method does.
*/
catList += ["Sylvester"]

배열의 특정 인덱스에 데이터 추가하기

배열의 특정 인덱스에 데이터 추가하기

이전 예시에서 append 메서드로 추가한 값은 배열의 끝에 추가됩니다. 하지만 경우에 따라 특정 인덱스에 추가하고 싶을 수 있습니다. 이때 insert 메서드를 사용합니다.

구문은 다음과 같습니다.

myArr.insert ("The data to add", at: index);

예시를 통해 알아보겠습니다.

var catList = ["Tom"]

catList.insert("Garfield", at: 1)

print(catList)

배열의 특정 요소 삭제하기

배열의 특정 요소 삭제하기

배열의 특정 인덱스에 있는 요소를 삭제할 때 remove 메서드를 사용합니다.

var shoppingList = ["Apple", "Cherry", "Cheese"]

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

let shoppingListTwo = shoppingList.removeLast()
// the last item in the array has just been removed

print(shoppingListTwo)

배열 순회

for-in을 사용하여 가지고 있는 배열을 순회할 수 있습니다.

예제를 살펴보겠습니다.

var shoppingList = ["Banana", "Orange", "Milk"]

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

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

집합

집합

같은 타입의 값들을 순서 없이 함께 저장할 때 사용합니다.

이름에서 알 수 있듯이 집합입니다. 집합에는 같은 값을 가진 요소가 두 개 이상 포함될 수 없습니다.

빈 집합 만들기

다음 예제와 같이 빈 집합을 만듭니다.

var catSet = Set<Character>()

배열 리터럴을 사용하여 집합 만들기

배열 리터럴을 사용하여 집합 만들기

배열 리터럴을 사용하여 집합을 만들 수 있습니다. 여기에 할당된 값이 배열처럼 보이지만 변수의 타입은 집합 <문자열>이라는 점에 유의하시기 바랍니다.

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

주의

배열 리터럴을 사용하면 타입을 정의하지 않고는 집합을 만들 수 없습니다. 배열과 혼동될 수 있기 때문입니다. 따라서 타입을 정의해야 합니다. 

적어도 다음과 같이 사용해야 합니다.

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

집합 메서드

집합 메서드

예제를 살펴보겠습니다.

var favoriteGenres = ["Funk"]

print("I have \(favoriteGenres.count) favorite music genres.")

if favoriteGenres.isEmpty {
    print("favoriteGenres is empty")
} else {
    print("I have particular music preferences.")
}

if favoriteGenres.contains("Funk") {
    print("Funk")
} 

집합 순회

집합 순회

Swift의 집합 타입에는 순서가 없습니다. 하지만 집합 값을 순회할 때 sorted 메서드를 사용할 수 있습니다. 이 메서드는 집합의 요소를 배열로 정렬합니다.

let favoriteGenres = ["Classical","Jazz", "Hip hop"]

for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop

사전

사전

사전은 값을 키와 값의 쌍으로 저장하며 순서가 없는 컬렉션 타입입니다.

각 값은 고유한 키와 함께 저장됩니다. 이 키는 사전에서 해당 값을 식별하는 ID입니다. 배열처럼 순서가 정해져 있지 않습니다. 실생활의 사전을 떠올리면 이해하기 쉽습니다.

따라서 각 값의 식별이 순서보다 중요합니다.

사전 타입은 [키: 값]이라는 축약형으로 정의할 수 있습니다. 일반적으로 축약형을 더 많이 사용합니다.

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

사전 접근 메서드

count 메서드를 사용하면 사전에 포함된 요소의 개수를 확인할 수 있습니다.

또한 isEmpty 메서드로 사전이 비어 있는지 확인할 수 있습니다.

이 메서드들을 사용하는 예제를 살펴보겠습니다.

var airports = ["LHR": "London", "IST": "Istanbul"]

print("The airports dictionary contains \(airports.count) items.")
// Prints "The airports dictionary contains 2 items."

if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// Prints "The airports dictionary is not empty."

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

첨자

첨자를 사용하여 값을 가져오는 과정은 다음과 같습니다. 반환 결과는 선택적 값입니다.

var airports = ["DUB":"Dublin"]

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// Prints "The name of the airport is Dublin Airport."



//Deletion
airports["APL"] = nil

if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airport's name is \(removedValue).")
} else {
    print("The airports dictionary does not contain a value for DUB.")
}
// Prints "The removed airport's name is Dublin Airport."

사전 업데이트

앞에서 살펴본 첨자 사용 방법 외에도 사전을 업데이트하는 메서드가 있습니다.

이 메서드는 업데이트가 완료된 후 업데이트되기 전의 값을 oldValue로 반환한다는 특징이 있습니다.

var airports = ["DUB": "Dublin"]

if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}
// Prints "The old value for DUB was Dublin."

사전에서 배열로 변환하는 예제는 다음과 같습니다

사전에서 배열로 변환하는 예제는 다음과 같습니다.


let airports = ["IST":"Istanbul Airport", "DUB":"Dublin Airport"]

let airportCodes = [String](airports.keys)
print(airportCodes)

let airportNames = [String](airports.values)
print(airportNames)

축하합니다

축하합니다 🎉

이번 레슨에서는 스위프트에서 컬렉션을 사용하는 방법을 배웠습니다.

다음 레슨에서 뵙겠습니다.

컬렉션 — 일러스트레이션 22

자주 묻는 질문

“컬렉션” 강의는 무료인가요?

네 — “컬렉션” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Swift Academy 강의 전체를 잠금 해제할 수 있습니다. Swift Academy 강의에는 총 1개의 강의가 포함되어 있습니다.

“컬렉션”에서 뭘 배우나요?

컬렉션 브라우저에서 직접 실행하는 실습 코드로 Swift Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Swift Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Swift Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 1개 중 1번째 강의입니다.

“컬렉션” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Swift Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Swift Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

← Swift Academy(으)로 돌아가기