* 내가 읽으려고 내 맘대로 번역한 글.

* 원문 : https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html

 

 

 

Collection Types

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

swift는 값의묶음을 저장하기 위해서 3가지 기본 타입을 제공한다 (array, set, dictionary)

Array : 순서가 있는 묶음값이다 (중복 가능)

Set : 순서가 없는 묶음값이다 (중복 불가능)

Dictionary : 순서가 없는 키-값 묶음값이다 (key는 중복 불가능)

 

 

Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you cannot insert a value of the wrong type into a collection by mistake. It also means you can be confident about the type of values you will retrieve from a collection.

array, set, dictionary는 저장할수 있는 키와 값의 타입이 명확해서 너가 실수로 잘못된 타입을 넣을수 없다.

그래서 값을 가져올때도 이상한 데이타 타입이 나오지 않는다고 확신할수 있다.

 

NOTE

Swift’s array, set, and dictionary types are implemented as generic collections. For more about generic types and collections, see Generics.

array, set, dictionary 는 generic collection을 구현했다.

 

Mutability of Collections

If you create an array, a set, or a dictionary, and assign it to a variable, the collection that is created will be mutable. This means that you can change (or mutate) the collection after it’s created by adding, removing, or changing items in the collection. If you assign an array, a set, or a dictionary to a constant, that collection is immutable, and its size and contents cannot be changed.

변수에 할당된 array, set, dictionary 는 값을 바꿀수 있다.

컬렉션에 아이템을 추가, 삭제, 변경할수 있다.

상수에 할당하면 바꿀수 없다. (크기도, 내용도). 당연한 소리.

 

NOTE

It is good practice to create immutable collections in all cases where the collection does not need to change. Doing so makes it easier for you to reason about your code and enables the Swift compiler to optimize the performance of the collections you create.

웬만하면 상수로 만들어라. 그러면 코드을 읽기 쉬워지고, 컴파일러 성능도 좋아진다.

 

Arrays

An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.

배열은 정렬된 목록에 같은 타입의 값을 저장한다. 같은 값을 다른 위치에 여러번 넣을수 있다.

 

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.

swift의 Array 타입은 Foundation의 NSArray 클래스와 연결된다.

 

Array Type Shorthand Syntax

The type of a Swift array is written in full as Array<Element>, where Element is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [Element]. Although the two forms are functionally identical, the shorthand form is preferred and is used throughout this guide when referring to the type of an array.

길게 쓰면 Array<배열이 저장할 데이타 타입>

짧게 쓰면 [배열이 저장할 데이타 타입]

두 가지 형식은 기능상으로 똑같고, 이 문서에서는 짧은 형식을 더 선호한다.

 

Creating an Empty Array

You can create an empty array of a certain type using initializer syntax:

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

 

Note that the type of the someInts variable is inferred to be [Int] from the type of the initializer.

Alternatively, if the context already provides type information, such as a function argument or an already typed variable or constant, you can create an empty array with an empty array literal, which is written as [] (an empty pair of square brackets):

someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]

 

Creating an Array with a Default Value

Swift’s Array type also provides an initializer for creating an array of a certain size with all of its values set to the same default value. You pass this initializer a default value of the appropriate type (called repeating): and the number of times that value is repeated in the new array (called count):

Double 값 0.0 을 3개 가지는 배열 만들기

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

You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array’s type is inferred from the type of the two arrays you add together:

배열 2개를 + 해서 새로운 배열 만들기. 데이타 타입은 같아야 함.

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

You can also initialize an array with an array literal, which is a shorthand way to write one or more values as an array collection. An array literal is written as a list of values, separated by commas, surrounded by a pair of square brackets:

  1. [value 1, value 2, value 3]

 

The example below creates an array called shoppingList to store String values:

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

 

The shoppingList variable is declared as “an array of string values”, written as [String]. Because this particular array has specified a value type of String, it is allowed to store String values only. Here, the shoppingList array is initialized with two String values ("Eggs" and "Milk"), written within an array literal.

 

NOTE

The shoppingList array is declared as a variable (with the var introducer) and not a constant (with the let introducer) because more items are added to the shopping list in the examples below.

shoppingList 배열은 나중에 아이템을 더 추가할수 있도록 변수로 선언되어 있다.

 

In this case, the array literal contains two String values and nothing else. This matches the type of the shoppingList variable’s declaration (an array that can only contain String values), and so the assignment of the array literal is permitted as a way to initialize shoppingList with two initial items.

 

Thanks to Swift’s type inference, you don’t have to write the type of the array if you’re initializing it with an array literal containing values of the same type. The initialization of shoppingList could have been written in a shorter form instead:

배열의 초기값으로 문자열을 주었기 때문에 [String] 을 안 써도 된다.

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

Because all values in the array literal are of the same type, Swift can infer that [String] is the correct type to use for the shoppingList variable.

 

Accessing and Modifying an Array

You access and modify an array through its methods and properties, or by using subscript syntax.

To find out the number of items in an array, check its read-only count property:

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

 

Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0:

  1. if shoppingList.isEmpty {
  2. print("The shopping list is empty.")
  3. } else {
  4. print("The shopping list is not empty.")
  5. }
  6. // Prints "The shopping list is not empty."

 

You can add a new item to the end of an array by calling the array’s append(_:) method:

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

 

Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):

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

 

Retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array:

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

 

NOTE

The first item in the array has an index of 0, not 1. Arrays in Swift are always zero-indexed.

You can use subscript syntax to change an existing value at a given index:

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

 

When you use subscript syntax, the index you specify needs to be valid. For example, writing shoppingList[shoppingList.count] = "Salt" to try to append an item to the end of the array results in a runtime error.

배열끝에 항목을 추가하려고 shoppingList[shoppingList.count] = "Salt" 하면 런타임 에러.

 

You can also use subscript syntax to change a range of values at once, even if the replacement set of values has a different length than the range you are replacing. The following example replaces "Chocolate Spread", "Cheese", and "Butter" with "Bananas"and "Apples":

배열첨자를 사용해서 범위의 값도 한번에 바꿀수 있다.

심지어 새로 넣을 배열의 갯수가 바꿀 갯수랑 달라도 가능함 -> 우왕 신기하다.

아래 예제에서 4, 5, 6 번째 항목이 Bananas, Apples 로 2개로 바뀜.

(배열의 크기가 7에서 6으로 줄어듬.)

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

 

To insert an item into the array at a specified index, call the array’s insert(_:at:) method:

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

 

This call to the insert(_:at:) method inserts a new item with a value of "Maple Syrup" at the very beginning of the shopping list, indicated by an index of 0.

 

Similarly, you remove an item from the array with the remove(at:) method. This method removes the item at the specified index and returns the removed item (although you can ignore the returned value if you do not need it):

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

 

NOTE

If you try to access or modify a value for an index that is outside of an array’s existing bounds, you will trigger a runtime error. You can check that an index is valid before using it by comparing it to the array’s count property. The largest valid index in an array is count - 1 because arrays are indexed from zero—however, when count is 0 (meaning the array is empty), there are no valid indexes.

index가 범위를 넘어가면 런타임 에러.

index 는 0 ~ count -1 까지

 

Any gaps in an array are closed when an item is removed, and so the value at index 0 is once again equal to "Six eggs":

  1. firstItem = shoppingList[0]
  2. // firstItem is now equal to "Six eggs"

If you want to remove the final item from an array, use the removeLast() method rather than the remove(at:) method to avoid the need to query the array’s count property. Like the remove(at:) method, removeLast() returns the removed item:

removeLast()

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

 

Iterating Over an Array

You can iterate over the entire set of values in an array with the for-in loop:

for-in 루프에 배열을 사용할수 있다.

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

 

If you need the integer index of each item as well as its value, use the enumerated() method to iterate over the array instead. For each item in the array, the enumerated() method returns a tuple composed of an integer and the item. The integers start at zero and count up by one for each item; if you enumerate over a whole array, these integers match the items’ indices. You can decompose the tuple into temporary constants or variables as part of the iteration:

반복문에서 배열의 값 대신에 숫자 index가 필요하다면, enumerated() 메소드를 사용해라.

배열의 각 요소에 대해서 enumerated() 메소드는 숫자와 항목으로 이루어진 tuple을 리턴한다.

숫자는 0부터 시작해서 각 항목마다 하나씩 증가 한다.

전체 배열을 열거하면, 이 숫자는 항목의 index들과 일치한다.

리턴된 tuple은 분해해서 상수나 변수에 넣을수 있다.

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

 

For more about the for-in loop, see For-In Loops.

 

Sets

이석우 추가 : 나는 objective-c 로 작업할때도 NSArray 와 NSDictionary는 많이 쓰지만 NSSet은 써본적이 없는거 같다.

그래서 대충 넘어가자...

 

A set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.

Set 순서가 없고 같은 타입의 유일한 값을 저장한다.

순서가 중요하지 않거나, 중복되지 않는 값이 필요할때는 배열대신 Set을 사용해라.

 

NOTE

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

For more information about using Set with Foundation and Cocoa, see Bridging Between Set and NSSet.

swift의 Set 은 Foundations의 NSSet 클래스와 연결되어 있다.

 

Hash Values for Set Types

A type must be hashable in order to be stored in a set—that is, the type must provide a way to compute a hash value for itself. A hash value is an Int value that is the same for all objects that compare equally, such that if a == b, it follows that a.hashValue == b.hashValue.

set에 저장하기 위해서는 데이타 타입이 반드시 hashable 해야 한다.

즉 데이타타입이 hash 값을 계산하는 방법을 제공해야 한다는 뜻이다.

hash는 Int 값이고, 같은 객체들은 같은 hash 값을 가진다.

즉 a == b 이면, a.hashValue == b.hashValue 다.

 

All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and can be used as set value types or dictionary key types. Enumeration case values without associated values (as described in Enumeration) are also hashable by default.

swift의 기본 데이타 타입들은(String, Int, Double, Bool) 기본적으로 hashable 해서,

set 이나 dictionary의 key 에 사용할수 있다.

 

NOTE

You can use your own custom types as set value types or dictionary key types by making them conform to the Hashable protocol from Swift’s standard library. Types that conform to the Hashable protocol must provide a gettable Int property called hashValue. The value returned by a type’s hashValue property is not required to be the same across different executions of the same program, or in different programs.

Because the Hashable protocol conforms to Equatable, conforming types must also provide an implementation of the equals operator (==). The Equatable protocol requires any conforming implementation of == to be an equivalence relation. That is, an implementation of == must satisfy the following three conditions, for all values a, b, and c:

너가 자신만의 데이타 타입을 만들고 swift 표준 라이브러리에 있는 Hashable protocol을 준수한다면 set 이나 dictionary의 key에 사용할수 있다. Hashable protocol을 준수하려면 hashValue 라는 속성을 만들어서 Int 값을 제공할수 있어야 한다.

같은 프로그램이 다른 프로세스로 여러개 실행될때나, 아예 서로 다른 프로그램 에서는 hashValue 속성이 리턴하는 값이 달라도 된다.

(이석우 추가 : 하나의 프로세스 안에서만 hashValue가 같으면 된다는 뜻 같음)

Hashable protocol은 Equatable을 구현하기 때문에, 반드시 == 연산자의 구현을 제공해야 한다.

== 를 구현하는것은 모든 값에 대해서 다음의 3가지 조건(a, b, c)을 만족해야만 한다.

  • a == a (Reflexivity)
  • a == b implies b == a (Symmetry)
  • a == b && b == c implies a == c (Transitivity)

For more information about conforming to protocols, see Protocols.

 

Set Type Syntax

The type of a Swift set is written as Set<Element>, where Element is the type that the set is allowed to store. Unlike arrays, sets do not have an equivalent shorthand form.

문법은 Set<Set이 저장할 데이타 타입>

배열과 다르게 짧은 표기법은 없다.

Creating and Initializing an Empty Set

You can create an empty set of a certain type using initializer syntax:

저장할 데이타 타입을 확실히 정하고 빈 Set을 만들수 있다.

var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// Prints "letters is of type Set<Character> with 0 items."

 

NOTE

The type of the letters variable is inferred to be Set<Character>, from the type of the initializer.

letters 변수는 초기화에 의해서 Set<Character> 타입으로 간주된다.

 

Alternatively, if the context already provides type information, such as a function argument or an already typed variable or constant, you can create an empty set with an empty array literal:

대신 함수의 매개변수나 이미 타입이 정의된 변수 또는 상수처럼 이미 타입정보를 알수 있으면

빈배열 문법으로 빈Set을 만들수 있다.

(이석우 추가 : [] 빈 배열 만드는 문법으로 빈Set 을 만들수 있다고???)

letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>

 

Creating a Set with an Array Literal

You can also initialize a set with an array literal, as a shorthand way to write one or more values as a set collection.

The example below creates a set called favoriteGenres to store String values:

set을 초기화할때 축약된 배열 문법으로 하나이상의 값을 넣을수 있다.

아래 예제는 favoriteGenres 라는 문자열을 저장하는 set을 만든다.

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items

 

The favoriteGenres variable is declared as “a set of String values”, written as Set<String>. Because this particular set has specified a value type of String, it is only allowed to store String values. Here, the favoriteGenres set is initialized with three Stringvalues ("Rock", "Classical", and "Hip hop"), written within an array literal.

favoriteGenres 변수는 Set<String> 문법으로 문자열 만 을 저장할 set 으로 정의되었다.

 

NOTE

The favoriteGenres set is declared as a variable (with the var introducer) and not a constant (with the let introducer) because items are added and removed in the examples below.

favoriteGenres set은 var 키워드를 사용해서 변수로 선언되었다. let 을 사용한 상수가 아니다.

왜냐면 아래의 예제에서 항목을 추가하고 삭제하려고.

 

A set type cannot be inferred from an array literal alone, so the type Set must be explicitly declared. However, because of Swift’s type inference, you don’t have to write the type of the set’s elements if you’re initializing it with an array literal that contains values of just one type. The initialization of favoriteGenres could have been written in a shorter form instead:

set 타입은 배열 문법만으로는 타입을 추론할수 없으니까, 정확히 선언되어야 한다.

swift가 타입을 추론하니까, 하나의 타입값을 포함한 배열 초기화 문법을 이용해서 set을 초기화할때 타입을 써줄필요가 없다.

favoriteGenres 초기화는 아래처럼 짧게 쓸수 있다.

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

Because all values in the array literal are of the same type, Swift can infer that Set<String>is the correct type to use for the favoriteGenres variable.

배열의 모든 값이 같은 타입이라서, swift가 Set<String> 이라고 올바른 타입을 추론할수 있다.

 

Accessing and Modifying a Set

You access and modify a set through its methods and properties.

To find out the number of items in a set, check its read-only count property:

  1. print("I have \(favoriteGenres.count) favorite music genres.")
  2. // Prints "I have 3 favorite music genres."

Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0:

  1. if favoriteGenres.isEmpty {
  2. print("As far as music goes, I'm not picky.")
  3. } else {
  4. print("I have particular music preferences.")
  5. }
  6. // Prints "I have particular music preferences."

You can add a new item into a set by calling the set’s insert(_:) method:

  1. favoriteGenres.insert("Jazz")
  2. // favoriteGenres now contains 4 items

You can remove an item from a set by calling the set’s remove(_:) method, which removes the item if it’s a member of the set, and returns the removed value, or returns nil if the set did not contain it. Alternatively, all items in a set can be removed with its removeAll()method.

  1. if let removedGenre = favoriteGenres.remove("Rock") {
  2. print("\(removedGenre)? I'm over it.")
  3. } else {
  4. print("I never much cared for that.")
  5. }
  6. // Prints "Rock? I'm over it."

To check whether a set contains a particular item, use the contains(_:) method.

  1. if favoriteGenres.contains("Funk") {
  2. print("I get up on the good foot.")
  3. } else {
  4. print("It's too funky in here.")
  5. }
  6. // Prints "It's too funky in here."

 

Iterating Over a Set

You can iterate over the values in a set with a for-in loop.

  1. for genre in favoriteGenres {
  2. print("\(genre)")
  3. }
  4. // Classical
  5. // Jazz
  6. // Hip hop

For more about the for-in loop, see For-In Loops.

Swift’s Set type does not have a defined ordering. To iterate over the values of a set in a specific order, use the sorted() method, which returns the set’s elements as an array sorted using the < operator.

  1. for genre in favoriteGenres.sorted() {
  2. print("\(genre)")
  3. }
  4. // Classical
  5. // Hip hop
  6. // Jazz

 

Performing Set Operations

You can efficiently perform fundamental set operations, such as combining two sets together, determining which values two sets have in common, or determining whether two sets contain all, some, or none of the same values.

 

Fundamental Set Operations

The illustration below depicts two sets—a and b—with the results of various set operations represented by the shaded regions.

  • Use the intersection(_:) method to create a new set with only the values common to both sets.
  • Use the symmetricDifference(_:) method to create a new set with values in either set, but not both.
  • Use the union(_:) method to create a new set with all of the values in both sets.
  • Use the subtracting(_:) method to create a new set with values not in the specified set.
  1. let oddDigits: Set = [1, 3, 5, 7, 9]
  2. let evenDigits: Set = [0, 2, 4, 6, 8]
  3. let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
  4.  
  5. oddDigits.union(evenDigits).sorted()
  6. // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  7. oddDigits.intersection(evenDigits).sorted()
  8. // []
  9. oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
  10. // [1, 9]
  11. oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
  12. // [1, 2, 9]

 

Set Membership and Equality

The illustration below depicts three sets—a, b and c—with overlapping regions representing elements shared among sets. Set a is a superset of set b, because a contains all elements in b. Conversely, set b is a subset of set a, because all elements in b are also contained by a. Set b and set c are disjoint with one another, because they share no elements in common.

  • Use the “is equal” operator (==) to determine whether two sets contain all of the same values.
  • Use the isSubset(of:) method to determine whether all of the values of a set are contained in the specified set.
  • Use the isSuperset(of:) method to determine whether a set contains all of the values in a specified set.
  • Use the isStrictSubset(of:) or isStrictSuperset(of:) methods to determine whether a set is a subset or superset, but not equal to, a specified set.
  • Use the isDisjoint(with:) method to determine whether two sets have no values in common.
  1. let houseAnimals: Set = ["🐶", "🐱"]
  2. let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
  3. let cityAnimals: Set = ["🐦", "🐭"]
  4.  
  5. houseAnimals.isSubset(of: farmAnimals)
  6. // true
  7. farmAnimals.isSuperset(of: houseAnimals)
  8. // true
  9. farmAnimals.isDisjoint(with: cityAnimals)
  10. // true

 

Dictionaries

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word.

Dictionary는 순서없는 동일타입의 key와 동일타입의 value 를 묶어서 저장한다.

각 value는 구분자 역활을 하는 유일한 key와 연결되어 있다.

배열의 항목들과 달리 Dictionary의 항목들은 정해진 순서가 없다.

우리가 진짜 사전(책으로 된 사전)을 사용해서 특정단어의 뜻을 찾듯이

Dictionary를 사용해서 특정 key를 사용해서 값을 찾을수 있다.

 

NOTE

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

For more information about using Dictionary with Foundation and Cocoa, see Bridging Between Dictionary and NSDictionary.

swift의 Dictionary는 Foundation의 NSDictionary와 연결되어 있다.

 

Dictionary Type Shorthand Syntax

The type of a Swift dictionary is written in full as Dictionary<Key, Value>, where Key is the type of value that can be used as a dictionary key, and Value is the type of value that the dictionary stores for those keys.

Dictionary<Key, Value>

 

NOTE

A dictionary Key type must conform to the Hashable protocol, like a set’s value type.

Key에 사용할 데이타타입은 반드시 Hashable protocol 을 준수해야 한다.

 

You can also write the type of a dictionary in shorthand form as [Key: Value]. Although the two forms are functionally identical, the shorthand form is preferred and is used throughout this guide when referring to the type of a dictionary.

짧게 쓰면 [Key: Value]

이 가이드에서는 짧게 쓸거다.

 

Creating an Empty Dictionary

As with arrays, you can create an empty Dictionary of a certain type by using initializer syntax:

특정 타입을 지정해서 초기화 하고 빈 Dictionary를 만들수 있다.

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

 

This example creates an empty dictionary of type [Int: String] to store human-readable names of integer values. Its keys are of type Int, and its values are of type String.

If the context already provides type information, you can create an empty dictionary with an empty dictionary literal, which is written as [:] (a colon inside a pair of square brackets):

앞에 Array, Set 과 같은 내용이니까 스킵...

  1. namesOfIntegers[16] = "sixteen" -> 이건 다른 언어들에서 사용하는 배열처럼 보여서 헷갈리겠다.
  2. // namesOfIntegers now contains 1 key-value pair
  3. namesOfIntegers = [:]
  4. // namesOfIntegers is once again an empty dictionary of type [Int: String]

 

Creating a Dictionary with a Dictionary Literal

You can also initialize a dictionary with a dictionary literal, which has a similar syntax to the array literal seen earlier. A dictionary literal is a shorthand way to write one or more key-value pairs as a Dictionary collection.

A key-value pair is a combination of a key and a value. In a dictionary literal, the key and value in each key-value pair are separated by a colon. The key-value pairs are written as a list, separated by commas, surrounded by a pair of square brackets:

위에서 밨었던 배열 형태와 비슷하게 생긴 문법으로, Dictionary를 초기화 할수 있다.

  1. [key 1: value 1, key 2: value 2, key 3: value 3]

The example below creates a dictionary to store the names of international airports. In this dictionary, the keys are three-letter International Air Transport Association codes, and the values are airport names:

  1. var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

The airports dictionary is declared as having a type of [String: String], which means “a Dictionary whose keys are of type String, and whose values are also of type String”.

 

NOTE

The airports dictionary is declared as a variable (with the var introducer), and not a constant (with the let introducer), because more airports are added to the dictionary in the examples below.

뒤에서 공항을 더 추가할거라서, airports Dictionary는 var 키워드를 이용해 변수로 만들었다. 상수가 아니고.

 

The airports dictionary is initialized with a dictionary literal containing two key-value pairs. The first pair has a key of "YYZ" and a value of "Toronto Pearson". The second pair has a key of "DUB" and a value of "Dublin".

This dictionary literal contains two String: String pairs. This key-value type matches the type of the airports variable declaration (a dictionary with only String keys, and only String values), and so the assignment of the dictionary literal is permitted as a way to initialize the airports dictionary with two initial items.

 

As with arrays, you don’t have to write the type of the dictionary if you’re initializing it with a dictionary literal whose keys and values have consistent types. The initialization of airportscould have been written in a shorter form instead:

초기화할때 Key, Value의 데이타 타입이 주어지니까, 아래처럼 줄여서 쓸수 있다.

  1. var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

Because all keys in the literal are of the same type as each other, and likewise all values are of the same type as each other, Swift can infer that [String: String] is the correct type to use for the airports dictionary.

 

Accessing and Modifying a Dictionary

You access and modify a dictionary through its methods and properties, or by using subscript syntax.

As with an array, you find out the number of items in a Dictionary by checking its read-only count property:

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

Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0:

  1. if airports.isEmpty {
  2. print("The airports dictionary is empty.")
  3. } else {
  4. print("The airports dictionary is not empty.")
  5. }
  6. // Prints "The airports dictionary is not empty."

 

You can add a new item to a dictionary with subscript syntax. Use a new key of the appropriate type as the subscript index, and assign a new value of the appropriate type:

Dictionary에 아이템 추가.

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

 

You can also use subscript syntax to change the value associated with a particular key:

아이템 수정.

  1. airports["LHR"] = "London Heathrow"
  2. // the value for "LHR" has been changed to "London Heathrow"

 

As an alternative to subscripting, use a dictionary’s updateValue(_:forKey:) method to set or update the value for a particular key. Like the subscript examples above, the updateValue(_:forKey:) method sets a value for a key if none exists, or updates the value if that key already exists. Unlike a subscript, however, the updateValue(_:forKey:) method returns the old value after performing an update. This enables you to check whether or not an update took place.

위에서 본 첨자를 사용하는 방식 대신, updateValue(_:forKey:) 메소드를 사용할수 있다.

이 메소드는 key가 없으면 새로 만들고, 있으면 수정한다.

이 메소드는 수정한뒤에 이전 값를 리턴한다. 그래서 수정여부를 확인할수 있다.

 

The updateValue(_:forKey:) method returns an optional value of the dictionary’s value type. For a dictionary that stores String values, for example, the method returns a value of type String?, or “optional String”. This optional value contains the old value for that key if one existed before the update, or nil if no value existed:

updateValue(_:forKey:) 메소드는 optional 타입으로 이전 값을 리턴한다.

문자열 값을 저장하는 Dictionary라면 이 메소드의 리턴값은 String? 또는 optional String 타입이다.

이 메소드는 key가 있으면 수정한후 이전값을 리턴하고

key가 없으면 새로 만들고, 이전 값은 없으니까 nil을 리턴한다. 그러니까 리턴값의 데이타 타입은 optional 이어야 함.

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."

 

You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

첨자를 사용해서 특정키에 대한 값을 꺼낼수 있다. 근데 Dictionary에 없는 키를 조회할수도 있으니까 리턴값을 optional 이다.

key가 있으면 값을 리턴하고, 없으면 nil 리턴함.

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."

 

You can use subscript syntax to remove a key-value pair from a dictionary by assigning a value of nil for that key:

첨자를 이용해서 nil을 넣으면 그 항목을 삭제 된다.

airports["APL"] = "Apple International"
// "Apple International" is not the real airport for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary

 

Alternatively, remove a key-value pair from a dictionary with the removeValue(forKey:)method. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed:

removeValue(forKey:) 메소드를 써서 지울수도 있다.

이 메소드는 Key가 있으면 삭제하고, 삭제된 값을 리턴한다.

Key가 없으면 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."

 

Iterating Over a Dictionary

You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

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

 

For more about the for-in loop, see For-In Loops.

You can also retrieve an iterable collection of a dictionary’s keys or values by accessing its keys and values properties:

for airportCode in airports.keys {
	print("Airport code: \(airportCode)")
}
// Airport code: LHR
// Airport code: YYZ

for airportName in airports.values {
	print("Airport name: \(airportName)")
}
// Airport name: London Heathrow
// Airport name: Toronto Pearson

 

If you need to use a dictionary’s keys or values with an API that takes an Array instance, initialize a new array with the keys or values property:

let airportCodes = [String](airports.keys)
// airportCodes is ["LHR", "YYZ"]

let airportNames = [String](airports.values)
// airportNames is ["London Heathrow", "Toronto Pearson"]

 

Swift’s Dictionary type does not have a defined ordering. To iterate over the keys or values of a dictionary in a specific order, use the sorted() method on its keys or values property.

Dictionary는 순서가 없으니까, keys 또는 values 를 순서대로 꺼내려면 sorted() 메소드를 사용해라.

반응형

'iOS 초보' 카테고리의 다른 글

[swift5.1번역] 6.Functions  (0) 2019.07.09
[swift5.1번역] 5.Control Flow  (0) 2019.07.03
[swift5.1번역] 3.Strings and Characters  (0) 2019.06.27
[swift5.1번역] 2.Basic Operators  (0) 2019.06.21
[swift5.1번역] 1.The Basics  (0) 2019.06.19
Posted by 돌비
,