Swift

[스위프트 기초] 5. 컬렉션타입(Array, Dictionary, Set)

microsaurs 2022. 5. 21. 19:40

<컬렉션 타입>

 

1. Array

- 멤버가 순서(인덱스)를 가진 리스트 형태의 컬렉션 타입

- 여러 가지 리터럴 문법을 활용할 수 있어 표현 방법이 다양함

 

 

// Array선언 및 생성

var integers: Array<Int> = Array<Int>()

 + 위와 동일한 표현 

var integers: ArrayMInt> = [Int]()

var integers: Array<Int> = []

var integers: [Int] = Array<Int>()

var integers: [Int] = [Int]()

var integers: [Int] = []

var integers = [int]()

 

// 멤버 추가 append

integers.append(1)

integers.append(100)

// 오류 발생 - Int 타입이 아니므로 멤버로 추가 X

integers.append(100.1) 

 

// 멤버 포함 여부 확인 contains

integers.contains(100) // true

ingegers.contains(99) // false

 

// 멤버 교체

integers[0] = 99

(타입) (교체 대상 인덱스) = (교체할 데이터)

 

//인덱스 제거 remove

integers.remove(at: 0)

integers.removeLast()

integers.removeAll()

 

// 멤버 수 확인 count

integers.count 

 

* 인덱스를 벗어나 접근하려면 익셉션 런타임 오류 발생

ex.

(현재 배열에 아무 데이터도 들어있지 않는 상태)

integers[0]  // 오류 발생

 

// 불변 Array: let을 사용하여 Array 선언

let immutableArray = [1,2,3]

* 수정이 불가능한 Array이므로 멤버를 추가하거나 삭제할 수 없음

//immutableArray.append(4) - 멤버 추가 불가 오류 발생

//immutableArrya.removeAll() -  멤버 삭제 불가 오류 발생

 

 

2. Dictionary

- 키와 값의 쌍으로 이루어진 컬렉션 타입

- Array와 비슷하게 여러 가지 리터러 ㄹ문법을 활용할 수 있어 표현 방법이 다양함

 

//Dictionary의 선언과 생성

//Key가 String 타입이고 Value가 Any인 빈 Dictionary 생성

var anyDictionary: Dictionary<String, Any> = [String: Any]()

 

 + 위와 동일한 표현 

var anyDictionary: Dictionary<String, Any> = DictionaryMString, Any>()

var anyDictionary: Dictionary<String, Any> = [:]

var anyDictionary: [String: Any] = Dictionary<String, Any>()

var anyDictionary: [String: Any] = [String: Any]()

var anyDictionary: [String: Any] = [:]

var anyDictionary = [String: Any]()

 

// 키에 할당하는 값 할당

anyDictionary["someKey"] = "value"

anyDictionary["anotherKey"] = 100

 

print(anyDictionary) 

=> ["someKey":"value","anotherKey":100] 출력

 

// 키에 해당하는 값 변경

anyDictionary["someKey"] = "dictionary"

print(anyDictionary)

=> ["someKey":"dictionary","anotherKey":100]

 

// 키에 해당하는 값 제거 removeValue

anyDictionary.removeValue(forKey: "anotherKey")

anyDictionary["someKey"] = nil

// 두 가지 방법이 거의 같은 방법이라고 볼 수 있음, 둘 다 키에 해당하는 값을 제거하는 방법

 

print(anyDictionary)

=> [:] (비어있는 딕셔너리가 됨)

 

// 불변 Dictionary: let을 사용하여 Dictionary 선언

let empthDictionary: [String: String] = [:]

let initalizedDictionary: [String: String] = ["name":"dingsi","gender":"female"]

* 불변 Dictionary 이므로 값 변경 불가

// emptyDictionary["key"] = "value" - 값 변경 및 추가 불가 오류 발생

 

3. Set

- 중복되지 않는 멤버가 순서 없이 존재하는 컬렉션

- Array, Dictionary와 다르게 축약형이 존재하지 않음

 

// Set 생성 및 선언

var integerSet: Set<Int> = Set<Int>()

 

// 새로운 멤버 입력 insert

* 동일한 값은 여러 번 insert해도 한 번만 저장

integerSet.insert(1)

integerSet.insert(99)

integerSet.insert(100)

integerset.insert(99)

 

print(integerSet) 

=> {100,99,1} 출력 // 99는 두 번 insert 했지만 한 번만 출력

 

// 멤버 포함 여부 확인 contains

print(integerSet.contains(1)) // true

print(integerSet.contains(2)) //  false

 

// 멤버 삭제 remove

integerSet.remove(99) 

print(integerSet) => {100.1}

 

integerSetremoveFirst()

print(integerSet) => {1}

 

// 멤버 개수 count

integerSet.count 

print(integerSet) => 1

 

* Set의 활용 _ 멤버의 유일성이 보장되기 때문에 집합 연산에 활용 가능

let setA: Set<Int> = [1,2,3,4,5]

let setB: Set<Int> = [3,4,5,6,7]

 

//합집합 union

let union: Set<Int>  =setA.union(setB)

print(union) => [2,3,4,5,6,3,1]

//합집합 오름차순 정렬 union.sorted

let sortedUnion: [Int] = union.sorted()

print(sortedUnion) => [1,2,3,4,5,6,7]

 

// 교집합 intersection

let intersection: Set<Int> = setA.intersection(setB)

print(intersection) => [5,3,4]

 

// 차집합 subtracting

let subtracting: Set<Int> = setA.subracting(setB)

print(subtracting) => [2,1]