[Swift] Collection Types

East Silver·2021년 12월 26일
0

Arrays

Creating an Empty Array

var someInts: [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]

Accessing and Modifying an Array

  • isEmpty
  • insert(_:at:)
  • remove(at:)
  • removeLast()

Sets

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

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:

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>

Accessing and Modifying a Set

  • isEmpty
  • insert(_:)
  • remove(_:)
  • removeAll()

Performing Set Operations

Fundamental Set Operations

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

Subset, Superset, Disjoint 중 어떤 관계인지 알 수 있다.
a - b: Superset
a - c: Subset
b - c: Disjoint

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

Dictionary 또한 한번 선언되어있으면 빈 딕셔너리가 되어도 Key와 Value의 타입이 변하지 않는다. 빈 Dictionary는 [:]로 표현할 수 있다.

namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

Accessing and Modifying a Dictionary

  • isEmpty
  • updateValue(_:forKey:)
  • removeValue(forKey:)
    Dictionary에서 특정한 Key 값에 접근할 때 Key 값이 존재하지 않을 수 있기 때문에 늘 옵셔널 값으로 결과를 준다. 즉 존재하지 않는 Key 값에 접근하면 nil을 반환시켜주는 것이다. 이렇기 때문에 옵셔널 바인딩을 활용해서 Value 값을 추출해 줘야 한다.
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 (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// LHR: London Heathrow
// YYZ: Toronto Pearson

Dictionary의 keys, values 프로퍼티로 각각 접근할 수도 있다.

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

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

To iterate over the keys or values of a dictionary in a specific order, use the sorted() method on its keys or values property.

profile
IOS programmer가 되고 싶다

0개의 댓글