티스토리 뷰

Swift 공식 가이드/Swift 4

Collection Types

찜토끼 2018. 9. 5. 19:00

Apple 제공 Swift 프로그래밍 가이드(4.2)의 Collection Types 부분을 공부하며 정리한 글입니다. 개인적인 생각, 이해를 돕기 위한 예제도 조금 들어가있습니다.


들어가며

Swift 에서는 값을 저장하기 위한 세 가지 Primary Collection type 을 제공합니다. Array, Set, Dictionary 입니다.

  • Array : 넣은 순서대로 저장되는 콜렉션

  • Set : 값이 중복되지 않는 순서없는 콜렉션

  • Dictionary : key-value 관계를 가지는 순서없는 콜렉션


이 콜렉션 타입들 역시 다른 상수 변수와 마찬가지로 type 체크에 엄격합니다. 즉 한번 저장할 값의 type 을 정하면 다른 type 의 값은 저장할 수 없습니다. (따라서 String, Int 같은 각기 다른 타입의 값들을 하나의 콜렉션에 저장하고 싶은 경우에는 Any 타입을 사용합니다. Any 타입에 대해서는 나중에 자세히 다룹니다.)

NOTE

 Array, Set, Dictionary 모두 generic collections 로 구현되었습니다. Generic type 과 콜렉션에 대해서는 Generics 에서 자세히 다룹니다.



Mutability of Collections

Array, set, dictionary 를 변수에 할당하면 mutable 이 되고 상수에 할당하면 immutable 이 됩니다.

  • mutable: 생성한 후에도 자유롭게 아이템을 추가/삭제할 수 있음

  • immutable: 생성한 후 콜렉션의 사이즈와 내용을 변경할 수 없음 (아이템 추가/삭제 불가)

NOTE

변경될 일이 없는 콜렉션은 immutable 로 만드는 것이 좋습니다. 코드가 좀 더 좋아질 뿐만 아니라 Swift 컴파일러의 최적화를 가능하게 해줍니다.




Arrays

Array 는 같은 타입의 값을 들어온 순서대로 저장합니다. 따라서 인덱스는 달라도 값은 같은 경우가 발생할 수 있습니다.

NOTE

Swift’s Array type is bridged to Foundation’s NSArray class.

For more information about using Array with Foundation and Cocoa, see Bridging Between Array and NSArray.



Array Type Shorthand Syntax

Array<Element> 타입을 [Element] 로 축약해서 나타낼 수 있습니다. (이때, Element 는 Array에 저장할 값의 타입)


Creating an Array

// 1. Creating an Empty Array
 
 // initializer syntax를 사용하여 Empty Array 생성하기
 
 var someInts = [Int]()
 
 print("someInts is of type [Int] with \(someInts.count) items.")
 
 // 출력결과: "someInts is of type [Int] with 0 items.”
 
 
 
 someInts.append(3)
 
 // 이제 someInts 에는 Int 타입의 값 1개가 들어있음
 
 someInts = []
 
 // 이제 someInts 는 empty Array
 
 // 그러나 someInts 는 여전히 [Int] 타입
 
 
 
 
 
 // 2. Creating Array with a Default Value
 
 // 특정 값이 N개 들어있는 Array 생성하기
 
 var threeDoubles = Array(repeating: 0.0, count: 3)
 
 // threeDoubles 는 [Double] 타입이며, equals [0.0, 0.0, 0.0]
 
 
 
 
 
 // 3. Creating an Array by Adding Two Arrays Together
 
 // 더하기 연산자(+)를 이용하여 두 Array 를 더해 새로운 Array 생성하기
 
 // 이때 두 Array 의 타입에 따라 새로운 Array 의 타입이 유추됨
 
 var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
 
 // anotherThreeDoubles 는 [Double] 타입이며, equals [2.5, 2.5, 2.5]
 
 
 
 var sixDoubles = threeDoubles + anotherThreeDoubles
 
 // sixDoubles 의 타입은 [Double] 로 유추되며, equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
 
 
 
 // 참고로 저장하는 타입이 다른 Array 끼리는 + 로 더하는 것이 불가능 (컴파일 에러)
 
 // 예를들어 [Double] 타입과 [Float] 타입의 배열은 + 를 통해 더할 수 없음
 
 // * 두 배열을 명시적으로 [Any] 타입으로 지정한다면 + 를 통해 더할 수 있음
 
 
 
 
 
 // 4. Creating an Array with an Array Literal
 
 // Array Literal 을 통해 Array 생성하기
 
 // * Array Literal: [값1, 값2, 값3] 형태로 값들을 콤마로 구분해 리스팅하고 대괄호로 묶기
 
 var shoppingList: [String= ["Eggs""Milk"]
 
 // shoppingList 은 두 개의 아이템들로 초기화 되었음
 
 
 
 // var shoppingList = ["Eggs", "Milk"]
 
 // 위와 같은 코드만 작성해도 shoppingList는 알아서 [String] 타입으로 유추됨
 
 // 두 아이템 "Eggs" 와 "Milk" 가 모두 String 타입이기 때문
 
 
 
 // var shoppingList = ["Eggs", 3]
 
 // 위 코드에서는 두 아이템 "Eggs" 와 3 의 타입이 다르기 때문에
 
 // shoppingList 의 타입 유추가 불가능 (컴파일 에러)
cs


Accessing and Modifying an Array

// 1. Array 안에 몇 개의 아이템이 있는지 알아보려면: count 프로퍼티 (read-only 속성임)
 
 print("The shopping list contains \(shoppingList.count) items.")
 
 // 출력: "The shopping list contains 2 items."
 
 
 
 
 
 // 2. Array 가 비어있는지 알아보려면: isEmpty 프로퍼티 (count == 0 일때 true)
 
 if shoppingList.isEmpty {
 
    print("The shopping list is empty.")
 
 } else {
 
    print("The shopping list is not empty.")
 
 }
 
 // 출력: "The shopping list is not empty.”
 
 
 
 
 
 // 3. Array 에 새로운 아이템을 맨 뒤에 추가하려면: append(_:) 메서드 호출
 
 shoppingList.append("Flour")
 
 // 이제 shoppingList 에는 3개의 아이템이 들어있으며, 팬케이크를 만들 수 있게 되었다!
 
 
 
 
 
 // 4. 연산자 += 를 이용해서 Array 에 다른 Array 를 더할 수도 있다
 
 // (물론 저장되는 값의 타입은 같아야 함)
 
 shoppingList += ["Baking Powder"]
 
 // 이제 shoppingList 에는 4개의 아이템이 들어있음
 
 shoppingList += ["Chocolate Spread""Cheese""Butter"]
 
 // 이제 shoppingList 에는 7개의 아이템이 들어있음
 
 
 
 
 
 // 5. Subscript 문법을 이용해서 Array 의 특정 값에 접근하려면:
 
 // Array 의 이름 뒤에 대괄호를 붙이고 그 안에 원하는 값의 인덱스를 넘기기
 
 var firstItem = shoppingList[0]
 
 // firstItem == "Eggs”
 
 // 참고로 Swift 의 Array 는 인덱스 0부터 시작한다. (1이 아님!)
 
 
 
 
 
 // 6. Subscript 문법을 이용해서 Array 의 특정 인덱스에 들어있는 값을 변경할 수 있다
 
 shoppingList[0= "Six eggs"
 
 // 이제 shoppingList 의 첫 번째 아이템은 "Eggs" 가 아닌 "Six eggs"
 
 
 
 // 인덱스를 통해 Array 에 접근할 때는 그 인덱스가 반드시 유효해야 한다!
 
 // 예를들어 shoppingList[shoppingList.count] = "Salt" 같은 코드는 런타임 에러를 발생시킨다
 
 // (* Array 의 맨 마지막 아이템에 해당하는 인덱스는 count-1)
 
 
 
 
 
 // 7. Subscript 문법을 이용해서 Array 의 특정 Range 를 특정 Array 로 교체할 수 있다
 
 // 개수는 일치하지 않아도 된다 (3개의 아이템이 들어있는 Range 를 2개의 아이템이 들어있는 Array 로 교체 가능)
 
 // * 당연히 타입은 일치해야 한다
 
 shoppingList[4...6= ["Bananas""Apples"]
 
 // 이제 shoppingList 는 6개의 아이템이 들어있음 (아이템 3개가 새로운 아이템 2개로 교체됨)
 
 
 
 // 보충설명
 
 var array:[Int= [0123456]
 
 array[2...5= [9// array는 [0, 1, 9, 6] 이 된다.
 
 array[0...4= [01234// 이런 식으로 범위를 넘은 Range 를 지정하면 런타임 에러 발생!
 
 // 값이 들어있는 인덱스에 대한 접근만 array[N] = value 또는 array[n...m] = [x, x, x] 문법 허용
 
 
 
 
 
 // 8. Array의 특정 위치에 새로운 아이템을 삽입하려면: insert(_:at:) 메서드
 
 shoppingList.insert("Maple Syrup", at: 0)
 
 // 이제 shoppingList 에는 7개의 아이템이 들어있음
 
 // "Maple Syrup" 은 shoppingList 의 맨 첫 번째 아이템
 
 
 
 // 보충설명
 
 array = [013]
 
 array.insert(2, at: 2// 2번 인덱스 자리에 2를 끼워넣겠다
 
 // [0, 1, 2, 3]
 
 
 
 array = [012]
 
 array.insert(3, at: 3// 3번 인덱스 자리에 3을 끼워넣겠다
 
 // [0, 1, 2, 3]
 
 
 
 array = [012]
 
 array.insert(4, at: 4// 4번 인덱스 자리에 4를 끼워넣겠다
 
 // 그러나 3번 인덱스에 값이 없으므로, 런타임 에러
 
 
 
 
 
 // 9. Array의 특정 위치에 있는 값을 삭제하려면: remove(at:) 메서드
 
 let mapleSyrup = shoppingList.remove(at: 0)
 
 // remove 메서드는 지정한 인덱스의 아이템을 remove하고 그 아이템의 값을 return 한다
 
 // mapleSyrup 상수에 들어있는 값은 shoppingList Array의 첫 번째 아이템이었던 "Maple Syrup"
 
 
 
 // 이제 shoppingList 에는 6개의 아이템이 들어있음
 
 
 
 firstItem = shoppingList[0]
 
 // "Six eggs”
 
 
 
 
 
 // 10. Array 의 맨 마지막 값을 삭제하려면: removeLast() 메서드
 
 let apples = shoppingList.removeLast()
 
 // apples 상수에 들어있는 값은 shoppingList 의 맨 마지막 아이템이었던 "Apples"
 
 // 가장 마지막 값을 삭제할 때는 remove(at:) 메서드보다 removeLast() 가 편리하다 (인덱스를 넘길 필요가 없으니)
cs


NOTE

Array 에 실제로 들어있는 아이템의 범위를 넘어선 인덱스를 통해 Array 의 아이템에 접근하려고 하면 런타임 에러가 발생하게 됩니다. 따라서 미리 인덱스의 유효성을 체크하는 것이 좋습니다. Array 의 count 프로퍼티를 확인해보세요. 유효한 인덱스 중 가장 큰 값은 count - 1 인 값입니다. Swift 에서는 Array 의 인덱스가 1이 아닌 0부터 시작하기 때문입니다. 만약 count 가 0 이라면 그 Array 에 유효한 인덱스는 없습니다. Empty Array 라는 뜻이기 때문입니다.



Iterating Over an Array

for-in 루프를 사용하여 Array 안의 모든 값을 순회할 수 있습니다:

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


배열의 값만이 아니라 인덱스도 순회가 필요한 경우에는 enumerated() 메서드를 사용하세요. (인덱스, 값) 쌍의 튜플을 순회할 수 있습니다.

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
cs


for-in 루프에 대한 더 자세한 정보는 For-In Loops 문서를 참조하세요.



Sets

Set 은 같은 타입의 값을, 중복없이, 순서없이 저장합니다. 저장하는 순서는 안 지켜져도 되지만 콜렉션 안의 값들이 유니크해야 할 때 Set 을 사용하세요.

NOTE

Swift’s Set type is bridged to Foundation’s NSSet class.


Hash Values for Set Types

Set 에 저장할 아이템의 타입은 반드시 hashable 해야 합니다.

  • Hashable 한 타입이란: 값의 hash value 를 계산해 제공할 수 있는 타입을 말함

  • Hash Value 란: a == b 일 때, a.hashValue == b.hashValue 를 만족하는 Int 값으로, 동일한 값은 항상 동일한 hash value 를 가짐

Swift의 모든 기본 타입(String, Int, Double, Bool 등)은 default로 hashable 합니다. 즉, 이런 타입들은 Set 에 저장될 수 있고 Dictionary 의 key 값도 될 수 있습니다. Int나 Bool 타입이 Dictionary Key로 쓰일 수 있다는 점이 Objective-C와 비교가 되네요. 참고로 Enum Case 의 값도 기본적으로 hashable 합니다(단, associated value 가 없는 경우).

NOTE

Custom Type을 Set 에 저장하거나 Dictionary 의 Key 타입으로 사용하고 싶다면 Hashable 프로토콜을 구현해야 합니다. 참고로 Hashable 프로토콜은 Equatable 프로토콜을 따르고 있으므로 equals 연산자 (==) 구현도 필요합니다.

Hashable 프로콜을 따르기 위해 필요한 구현을 정리하면

  • Int 타입의 hashValue 프로퍼티 getter

  • equals 연산자(==)를 구현하며 다음 세 조건을 만족

  1. a == a (Reflexivity)

  2. a == b 를 만족할 때, b == a (Symmetry)

  3. a == b && b == c 를 만족할 때, a == c (Transitivity)

프로토콜을 구현하는 방법에 대해 더 알고 싶다면 Protocols 문서를 참조하세요.



Set Type Syntax

Set<Element> 로 Set 을 만들 수 있습니다. 이때 Element 는 Set 에 저장될 아이템의 타입입니다. Set 은 Array 와 다르게 shorthand form 이 없습니다. 예를들어 var intArray: [Int] 는 Int 타입을 저장하는 Array 를 만들어주지만, 이와 유사하게 var intSet: <Int> 를 시도해보면 컴파일 에러가 발생합니다.


Creating and Initializing a Set

// 1. Empty Set 생성
 
 var letters = Set<Character>()
 
 print("letters is of type Set<character> with \(letters.count) items.")
 
 // 출력 "letters is of type Set<character> with 0 items.”
 
 
 
 letters.insert("a")
 
 // 이제 letters 에는 1개의 값(Character 타입)이 들어있음
 
 
 
 // 이미 Set 타입임을 알고 있는 경우에는 빈 Array 리터럴을 할당해 Empty Set 으로 만들 수도 있다
 
 letters = []
 
 // 이제 letters 는 Eempty Set 이고, 여전히 타입은 Set<Character> 이다
 
 
 
 
 
 // 2. Array 리터럴을 이용하여 Set 생성
 
 var favoriteGenres: Set<String> = ["Rock""Classical""Hip hop"]
 
 // favoriteGenres 는 3개의 아이템들로 초기화되었다
 
 
 
 var favoriteGenres2: Set = ["Rock""Classical""Hip hop"]
 
 // 위와 같이 저장할 아이템의 타입을 명시하지 않아도, Array 리터럴을 통해 String 타입이 저장될 Set 이라는 것을 유추해준다
 
 // 단, Set 이라고 명시하지 않으면 이 변수는 Array 가 되니 조심하자
cs



Accessing and Modifying a Set

// 1. Set 안에 몇 개의 Item이 있는지 알고 싶으면: count 프로퍼티 (read-only)
print("I have \(favoriteGenres.count) favorite music genres.")
// 출력 "I have 3 favorite music genres.”
 
 
// 2. Set 안이 비어있는지 알고 싶으면: isEmpty 프로퍼티 (count == 0 일때 true)
if favoriteGenres.isEmpty {
   print("As far as music goes, I'm not picky.")
else {
   print("I have particular music preferences.")
}
// 출력 "I have particular music preferences."
 
 
// 3. Set 에 Item 을 추가하려면: insert(_:) 메서드
favoriteGenres.insert("Jazz")
// 이제 favoriteGenres 에는 4개의 아이템이 들어있음
 
 
// 4. Set 에서 Item 을 제거하려면: remove(_:) 메서드
// 이 메서드는 Set 에서 Item 을 지우고 그 값을 리턴한다
// 만약 Item 이 Set 안에 없었다면 nil 을 리턴한다
// Set 안의 모든 아이템들을 한번에 지우려면 removeAll() 메서드를 사용할 것
if let removedGenre = favoriteGenres.remove("Rock") {
   print("\(removedGenre)? I'm over it.")
else {
   print("I never much cared for that.")
}
// 출력 "Rock? I'm over it.”
 
 
// 5. 특정 Item 이 Set 안에 들어있는지 알고 싶으면: contains(_:) 메서드
if favoriteGenres.contains("Funk") {
   print("I get up on the good foot.")
else {
   print("It's too funky in here.")
}
// 출력 "It's too funky in here."
cs



Iterating Over a Set

for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop
 
 
// Set 안의 Item을 특정 순서로 순회하고 싶다면 sorted() 메서드를 사용
// Item을 < 연산자로 sorting 한 array가 반환됨
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz
cs



Performing Set Operations

기본적인 Set Operation 을 쉽게 수행하는 방법에 대해 알아보겠습니다. 기본적인 Set Operation 의 예를 들어보면, 두 Set 을 합친다거나, 두 Set 에서 공통으로 가지는 값을 찾는다거나, 등등이 있습니다.

Fundamental Set Operations


위 그림에서의 ab 는 각각 Set 입니다. 각 벤다이어그램 위에 표기된 메서드는 벤다이어그램의 초록색 부분에 해당하는 Item 들로 구성된 새로운 Set 을 생성하여 리턴합니다. 자세한 설명은 생략하고 예제로 대체합니다.

let oddDigits: Set = [13579]
let evenDigits: Set = [02468]
let singleDigitPrimeNumbers: Set = [2357]
 
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
cs


Set Membership and Equality

위 그림에서 a, b, c 는 각각 Set 이며 absuperset, basubset, bc 는 서로에게 disjoint 한 관계입니다.

  • "is equal" operator (==): 두 Set 의 내용이 전부 동일한지? (Item의 type, count, value 모두)

  • isSubset(of:): subset 인지?

  • isSuperset(of:): superset 인지?

  • isStrictSubset(of:): subset이면서, subset != superset 인지?

  • isStrictSuperset(of:): superset이면서, subset != superset 인지?

  • isDisjoint(with:): 두 Set 간의 교집합이 없는지?

let houseAnimals: Set = ["🐶""🐱"]
let farmAnimals: Set = ["🐮""🐔""🐑""🐶""🐱"]
let cityAnimals: Set = ["🐦""🐭"]
 
houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true
 
 
// 추가설명
let myAnimals: Set = ["🐮""🐔"]
let myFriendAnimals: Set = ["🐮""🐔""🐑""🐶""🐱"]
 
myAnimals.isStrictSubset(of: farmAnimals)
// true
myFriendAnimals.isStrictSubset(of: farmAnimals)
// false
cs




Dictionaries

Dictionary 는 key-value 쌍을 순서없이 저장합니다. 이때 key 가 되는 타입끼리는 서로 같아야 하며 value 가 되는 타입끼리도 서로 같아야 합니다. Key 는 그 각각이 유니크하며 value 를 위한 identifier 역할을 합니다. 따라서 key 와 value 는 1:1 관계를 가집니다. 사전처럼 사용할 콜렉션 타입이 필요할 때 Dictionary 를 사용하면 유용합니다.

NOTE

Swift’s Dictionary type is bridged to Foundation’s NSDictionary class.


Dictionary Type Shorthand Syntax

Swift 에서 Dictionary 를 쓸 때는 Dictionary<Key, Value> 로 씁니다. 이때 Key 는 Dictionary 에서 Key 로 쓰일 타입이며 Value 는 Key 와 1:1 쌍으로 저장될 값의 타입을 뜻합니다. 이 폼은 [Key: Value] 로 축약할 수 있으며 이 축약형이 더 선호됩니다.

NOTE

Dictionary 의 Key 가 될 타입은 Hashable 해야 합니다. Set 에 저장될 타입처럼요. 이 둘은 유니크한 값인지를 따질 수 있어야 한다는 공통점이 있지요.


Creating a Dictionary

// 1. Creating an Empty Dictionary
var namesOfIntegers = [IntString]()
// namesOfIntegers 는 [Int: String] 타입의 Empty Dictionary
 
namesOfIntegers[16= "sixteen"
// namesOfIntegers 에는 이제 하나의 key-value 쌍이 들어있음
namesOfIntegers = [:]
// namesOfIntegers 는 다시 한 번 [Int: String] 타입의 Empty Dictionary 가 됨
 
 
// 2. Creating a Dictionary with a Dictionary Literal
var airports: [StringString= ["YYZ""Toronto Pearson""DUB""Dublin"]
 
// 아래와 같이만 써도 알아서 [String: String] 타입을 유추한다
var airports = ["YYZ""Toronto Pearson""DUB""Dublin"]
 
cs


Accessing and Modifying a Dictionary

// 1. 아이템 개수를 알아보고 싶으면: count 프로퍼티 (read-only)
print("The airports dictionary contains \(airports.count) items.")
// 출력 "The airports dictionary contains 2 items."
 
 
// 2. 비어있는지 알아보고 싶으면: isEmpty 프로퍼티 (count == 0 이면 true)
if airports.isEmpty {
    print("The airports dictionary is empty.")
else {
    print("The airports dictionary is not empty.")
}
// 출력 "The airports dictionary is not empty."
 
 
// 3. subscript syntax 를 사용해서 아이템 삽입 및 갱신하기
airports["LHR"= "London"
// airports 에는 이제 3개의 아이템이 들어있음
 
airports["LHR"= "London Heathrow"
// Key "LHR" 와 쌍을 이루는 Value 는 이제 "London Heathrow"
 
 
// 4. Subscript Syntax 안쓰고 아이템 삽입 및 갱신하기: updateValue(_:forKey:) 메서드
// dictionary[key] = value 와 같은 동작을 하지만 리턴값이 존재한다
// key 와 1:1 쌍을 이루는 value 가 이미 존재한다면 그 value 를 리턴하고
// 없다면 nil 을 리턴한다 (따라서 updateValue 메서드의 리턴 타입은 optional)
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    // 리턴값이 있다는 것은 즉 이미 존재하던 값에서 새로운 값으로 대체되었음을 말함
    print("The old value for DUB was \(oldValue).")
}
// 출력 "The old value for DUB was Dublin."
 
 
// 5. Subscript Syntax 를 사용해서 특정 key 와 1:1 쌍을 이루는 value 에 접근하기
if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
else {
    // key 에 해당하는 value 가 없다면 nil 을 반환한다
    print("That airport is not in the airports dictionary.")
}
// 출력 "The name of the airport is Dublin Airport.”
 
 
// 6. 특정 아이템 지우기 (key-value 쌍 자체를 지우기)
airports["APL"= "Apple International"
// "Apple International" 은 실제 공항이 아니니까 지워버리자!
airports["APL"= nil
// "APL"-"Apple International" 쌍은 이제 Dictionary 에서 지워졌다
 
 
// 7. 특정 아이템을 지우고 싶으면: removeValue(forKey:) 메서드
// 위에서 수행했던 dictionary[key] = nil 과 같은 동작을 하지만 리턴값이 존재한다
// key 와 1:1 쌍을 이루는 value 가 이미 존재한다면 그 value 를 리턴하고
// 없다면 nil 을 리턴한다 (따라서 removeValue 메서드의 리턴 타입은 optional)
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.")
}
// 출력 "The removed airport's name is Dublin Airport.”
cs


Iterating Over a Dictionary

for-in 루프를 통해 Dictionary 의 key-value 쌍을 순회할 수 있습니다. Dictionary 의 아이템 각각은 (key, value) 튜플을 반환하며, 이 튜플의 멤버를 분해하여 임시 상수/변수에 할당할 수 있습니다.

for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
cs


for-in 루프에 대해 더 알고 싶다면 For-In Loops 문서를 참조하세요.

Dictionary 의 key 리스트, 혹은 value 리스트만 순회하고 싶다면 keys, values 프로퍼티를 사용하세요.

for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR
 
for airportName in airports.values {
    print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow
cs


Dictionary 의 key 리스트나 value 리스트만을 Array 인스턴스로 사용할 일이 있다면, keys 나 values 프로퍼티를 사용해 Array 를 새로 초기화하도록 하세요.

let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
 
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]
cs


Swift 에서 Dictionary 타입은 순서를 가지지 않습니다. 만약 특정한 순서로 key 리스트나 value 리스트를 순회하기 원한다면 keysvalues 프로퍼티에 sorted() 메서드를 사용하세요.

// <참고> 뒷장에 나오는 부분인데 그냥 맛보기로. 클로저 모르시면 넘어가세요!
 
var dict: [StringString= ["b""bValue""a""aValue"]
 
// Dictionary 의 소팅은 이런 식으로 할 수 있다
let sortedDict = dict.sorted { (first, second) -> Bool in
    return first.key < second.key
}
// 위 코드에서의 first, second는 Dictionary 의 아이템(튜플 타입, key-value 쌍)
// 함수의 맨 마지막 파라미터로 클로저가 들어오면 괄호는 생략가능해서 이런 폼이 되었음
// sortedDict 에는 이제 ("a", "aValue") ("b", "bValue") 순서로 들어있다
 
// 또한 위 코드를 아래와 같이 축약할 수 있다
let sortedDict = dict.sorted { $0.0 < $1.0 }
// $0와 $1는 각각 첫 번째와 두 번째로 들어오는 파라미터
// return은 생략가능
cs



'Swift 공식 가이드 > Swift 4' 카테고리의 다른 글

Strings and Characters  (0) 2018.06.20
Basic Operators  (0) 2018.03.23
The basics  (0) 2018.03.02
A Swift Tour  (0) 2017.10.17
Version Compatibility  (0) 2017.10.04
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함