Swift 공식문서(4) - Collection Types

Jiyoon·2022년 4월 7일
0

iOS

목록 보기
13/16
post-thumbnail

Collection Types

Swift의 주요 컬렉션 타입들은 array, set, dictionary가 있다.

세 가지 타입 모두 담고 있는 키와 밸류에 대한 타입에 명시적이다. 즉슨, 실수로 다른 타입의 값을 넣을 수 없다는 뜻. 이 말은 해당 콜렉션에서 값을 받을 때 값의 타입에 대해 확신할 수 있다는 의미도 된다.

이러한 컬렉션 타입들을 변수에 할당하면 수정이 가능하며, 상수에 할당하면 수정이 불가하다.

Arrays

선언 방식: Array = [Type]

디폴트 값을 내재한 array 생성

repeating을 통해 어떤 값을 받을 지 정하고 count를 통해 몇 번 반복할 것인지 정한다

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

두 개의 array를 합쳐서 하나의 array로 반환 가능하다

같은 타입을 담고 있을 경우 합쳐서 하나의 array로 만들 수 있다

다른 타입의 컬렉션끼리 더하려고 할 경우, 에러가 난다

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]

Array Literal을 이용해 array 생성

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

위와 같이 바로 array에 할당을 해주면 swift가 알아서 타입을 추론해준다

Array에 접근하고 수정하기

shoppingList.count
shoppingList.isEmpty
shoppingList.append()
shoppingList += [item1, item2]
shoppingList[0] // subscript를 사용해서 변수에 값을 할당하거나 변경할 수 있다

shoppingList[2...4] = [item1] //subscript를 이용해서 array내의 값을 한 번에 바꿀 수도 있다(범위가 달라도 가능)
shoppingList.insert("hello", at: 0) //insert로 원하는 위치에 원하는 값을 넣을 수도 있다
shoppingList.remove(at: 0) //변수에 지운 값 반환 가능
shoppingList.removeLast() //변주에 지운 값 반환 가능

Array 반복하기

for item in shoppingList{
	print(item)
}

for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}

enumerated()를 사용하면 각 항목의 인덱스와 값을 함께 받을 수 있다

Sets

아이템의 순서가 중요하지 않을 때나 아이템이 한번만 나오는 것을 보장받고 싶을 때 array가 아닌 set을 쓴다

Set타입을 위한 해쉬값

Set 안에는 무조건 hashable 타입의 값이 들어가야 한다(기본적인 string, int, double, bool 전부 hashable)

만약 custom type을 만들고 set이나 dictionary의 key로 넣고 싶다면 Hashable 프로토콜을 따라야 한다.

Set 형태로 선언

빈 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>

이미 type을 정의해 놓은 빈 set이 있다면, 빈 array를 사용해서 빈 set을 정의해 줄 수 있다.

Array Literal을 사용해서 set 생성

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
// set은 array literal 혼자서로는 타입을 추론할 수 없다, 따라서 set이라는 타입이라고 명시해주어야 한다.

Set에 접근하고 수정하기

favoriteGenres.count
favoriteGenres.isEmpty
favoriteGenres.insert(item1) //array의 append와 같은 역할(값을 추가한다)
favoriteGenres.remove(item1) // 만약 set에 있다면 제거하고, 없다면 nil을 반환한다
favoriteGenres.contains(item1) // 특정 아이템의 포함 유무에 따라 true/false 반환

set 반복하기

for genre in favoriteGenres {
    print("\(genre)")
}
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}

정해진 순서가 없기 때문에 sorted() 메서드를 사용하면 정렬되어서 출력된다

Set 연산 수행하기

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 비교

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

houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true
houseAnimals == cityAnimals // set에 들어있는 모든 값이 같은지 비교
// false 

Dictionaries

키, 밸류 값으로 구성되어 있으며 순서가 없다.

Dictionary<Key, Value>로 선언할 수 있다, 더 짧은 폼은 [Key : Value]

빈 딕셔너리 만들기

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]

이미 딕셔너리 안의 키 밸류 값 타입을 추론할 수 있는 상황이라면 빈 딕셔너리를 간단하게 줄 수 있다.

Dictionary Literal을 사용해서 dictionary 만들기

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

Dictionary에 접근하고 수정하기

airports.count
airports.isEmpty
airports["key"] = "value" // subscript 활용해서 value 변경 가능

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"] { // subscript를 통해 접근한 값은 optional 값으로 반환된다
    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 // nil을 할당함으로써 key:value 쌍을 없앨 수 있다
// APL has now been removed from the dictionary

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

updateValue로 값을 업데이트 시켜주거나, 키가 없으면 키:밸류 쌍을 추가해준다

또한 dictionary의 이전 밸류를 옵셔널 값으로 반환해 준다(존재했으면 oprional(item1), 아니면 Nil)

Dictionary 반복하기

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

// 따로따로 반환 가능하다
for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
for airportName in airports.values {
    print("Airport name: \(airportName)")

// 바로 array에 할당할 수 있다
let airportCodes = [String](airports.keys)
// airportCodes is ["LHR", "YYZ"]

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

반복하게 되면 (key, value) 튜플 값을 반환하게 된다

순차적이지 않기 때문에 순서가 있게 값을 반환하고 싶으면 sorted() 메서드를 활용하면 된다

0개의 댓글