소소한개발팁
article thumbnail
반응형

Collection Types

- Swift에서는 값을 저장하기 위해 Array, Set, Dictionary를 제공합니다.

 

Mutability of Collections

- Array, Set, Dictionary 을 만들어 변수에 할당하면 생성된 컬렉션은 변경이 가능합니다. 하지만 성능 상 상수로 설정하여 관리하는 게 좋습니다.

 

Arrays

- 배열은 같은 유형의 값을 저장합니다. 동일한 값이라도 다른 위치에 저장될 수 있습니다.

 

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

 

- 아래의 보기는 배열에 값을 넣었다가 다시 빈 배열로 변경한 예시입니다.

 

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

- 아래의 보기는 기본값으로 배열을 생성한 예시입니다.

 

var threeDoubles = Array(repeating: 0.0, count: 3)
// 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]

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

- 아래의 보기는 리터럴을 사용한 예시입니다.

 

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

 

- 리터럴의 값이 같은 String 값이기 때문에 아래와 같이 생략하여 표시할 수 있습니다.

 

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

 

Accessing and Modifying an Array

- 아래의 보기는 배열의 항목수를 확인하는 예시입니다.

 

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

 

- 아래의 보기는 배열의 값의 유무를 체크하는 예시입니다.

 

if shoppingList.isEmpty {
  print("The shopping list is empty.")
} else {
  print("The shopping list isn't empty.")
}
// Prints "The shopping list isn't empty."

 

- 아래의 보기는 배열의 값을 append 를 이용하여 추가하는 예시입니다.

 

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

 

- 아래의 보기는 배열의 값을 (+=)를 이용하여 추가하는 예시입니다.

 

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

 

- 아래의 보기는 배열의 순서를 통해 값에 접근하는 예시입니다. 

 

var firstItem = shoppingList[0] 
// firstItem is equal to "Eggs" Swift에서 배열의 순서는 0부터 시작합니다.

 

- 아래의 보기는 배열의 순서에 해당 하는 값을 변경하는 예시입니다.

 

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

 

- 아래의 보기는 배열의 특정 값을 가져오는 예시입니다.

 

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

 

- 아래의 보기는 배열의 원하는 위치에 값을 추가하는 예시입니다.

 

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

 

- 아래의 보기는 배열의 원하는 위치에 값을 삭제하는 예시입니다.

 

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

 

- 아래의 보기는 변수에 배열의 특정값을 초기화하는 예시입니다.

 

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

 

- 아래의 보기는 배열의 마지막 값을 삭제하는 예시입니다.

 

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

 

 

Iterating Over an Array

- 아래의 보기는 for - in 루프를 사용하여 배열의 값을 출력하는 예시입니다.

 

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

 

- 아래의 보기는 for - in 루프를 사용하여 배열을 튜플 값으로 출력하는 예시입니다.

 

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

 

 

Sets

- Set 동일한 유형의 값이 순서 없이 저장됩니다. 항목의 순서가 중요하지 않거나 중복되는 값을 사용하지 않을 경우 사용하면 좋습니다.

 

 

Creating and Initializing an Empty 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."

 

- 아래의 보기는 빈 집합에 값을 추가한 후 다시 빈 집합으로 초기화하는 예시입니다.

 

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

- 아래의 보기는 리터럴을 사용한 예시입니다.

 

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

 

- 리터럴의 값이 같은 String 값이기 때문에 아래와 같이 생략하여 표시할 수 있습니다.

 

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

 

 

Accessing and Modifying a Set

- 아래의 보기는 집합의 숫자에 접근하는 예시입니다.

 

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

 

- 아래의 보기는 집합 값의 유무를 확인하는 예시입니다.

 

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

 

- 아래의 보기는 집합 값을 추가하는 예시입니다.

 

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

 

- 아래의 보기는 집합 값을 삭제하는 예시입니다.

 

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

 

- 아래의 보기는 집합 값에 특정항목이 있는지 확인하는 예시입니다.

 

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

 

 

Iterating Over a Set

- 아래의 보기는 for - in 루프를 사용하여 집합의 값을 출력하는 예시입니다.

 

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

 

- 아래의 보기는 정렬을 사용한 for - in 루프를 사용하여 집합의 값을 출력하는 예시입니다.

 

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

 

 

Fundamental Set Operations

 

  • 사용 intersection(_:) 두 집합에 공통되는 값만 사용하여 새 집합을 만드는 방법.
  • 사용 symmetricDifference(_:) 둘 다가 아니라 둘 다 설정된 값이 있는 새 집합을 만드는 방법.
  • 사용 union(_:) 두 집합의 모든 값을 사용하여 새 집합을 만드는 방법.
  • 사용 subtracting(_:) 지정된 집합에 없는 값을 사용하여 새 집합을 만드는 방법.

- 아래의 보기는 위에 대한 예시입니다.

 

let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

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]

 

 

Set Membership and Equality

 

  • 사용 isSubset(of:) 집합의 모든 값이 지정된 집합에 포함되는지 여부를 결정하는 방법.
  • 사용 isSuperset(of:) 집합에 지정된 집합의 모든 값이 포함되어 있는지 여부를 확인하는 방법.
  • 사용 isStrictSubset(of:) 또는 isStrictSuperset(of:) 집합이 지정된 집합이 아닌 부분 집합인지 또는 상위 집합인지 확인하는 방법.
  • 사용 isDisjoint(with:) 두 집합에 공통 값이 없는지 여부를 확인하는 방법.

 

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

 

 

Dictionaries

- 사전은 정의된 순서가 없는 컬렉션에 동일한 유형의 키와 동일한 유형의 값 사이의 연결을 저장합니다.

각 값은 사전에서 해당 값의 식별자 역할을 하는 고유한 키를 통해 접근할 수 있습니다. 또한 사전에는 정해진 순서가 존재하지 않습니다. 

 

 

Creating an Empty Dictionary

- 아래의 보기는 빈 사전을 초기화하는 예시입니다.

 

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]

 

 

Creating a Dictionary with a Dictionary Literal

- 아래의 보기는 리터럴을 사용한 예시입니다.

 

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

 

- 리터럴의 값이 같은 String, String 값이기 때문에 아래와 같이 생략하여 표시할 수 있습니다.

 

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

 

 

Accessing and Modifying a Dictionary

- 아래의 보기는 사전의 순서에 접근한 예시입니다.

 

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 isn't empty.")
}
// Prints "The airports dictionary isn't empty."

 

- 아래의 보기는 사전에 값을 추가하는 예시입니다.

 

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

 

- 아래의 보기는 사전에 값을 변경하는 예시입니다.

 

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

 

- 아래의 보기는 사전에 값을 변경한 후 이전 값을 반환하는 updateValue 예시입니다.

 

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

 

- 아래의 보기는 사전에 변경된 값이 저장된 예시입니다.

 

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

 

- 아래의 보기는 사전에 값을 제거하는 예시입니다.

 

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

 

- 아래의 보기는 사전에 값을 변경한 후 삭제된 값을 반환하는 removeValue 예시입니다.

 

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

 

 

Iterating Over a Dictionary

- 아래의 보기는 for - in 루프를 사용하여 사전에서 튜플의 값을 출력하는 예시입니다.

 

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

 

- 아래의 보기는 for - in 루프를 사용하여 사전에서 key 값과 value 값을 출력하는 예시입니다.

 

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

 

- 아래의 보기 사전의 값을 배열에 저장한 예시입니다.

 

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

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

 

- 사전은 순서가 존재하지 않으므로 정렬을 시켜주기 위해서는 sorted()를 사용하도록 합니다. 

 

 

내용은 https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html 를 보면서 작성하였고 원문으로 작성된 내용을 옮기다 보니 이상한 부분이 있을 수 있습니다. 자세한 내용은 위의 링크를 확인해주시기 바랍니다.

 

반응형
profile

소소한개발팁

@개발자 뱅

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!