Swift랑 친해지기/Swift문법정리

컬렉션 타입

데브킹덕 2021. 12. 1. 21:03

컬렉션 타입

- 여러 값들을 묶어서 하나의 변수라든지 표현할 수 있게 만들어줌

- Array

- Dictionary

- Set

 

Array - 순서가 있는 리스트 컬렉션

 

Code로 알아보기 

// 빈 Int Array 생성

var integers: Array<Int> = Array<Int>()        <----  Int타입의 빈 Array생성

integers.append(1)                                     <---- 요소를 추가해주고 싶다 append  메소드를 사용        결과[1]

integers.append(100)                                <----------                                                               결과[1, 100]

//integers.append(101.1)                            <----  Double, Float 타입을 넣어주게 되어 오류발생

 

integers.contains(100)   <------ 요녀석이 이런 멤버를 가지고 있는가?? contains 메소드를 사용       결과[true]

integers.contains(99)    <------                                                                                                        결과[false]

 

integers.remove(at: 0) <-----  index에 0번째(해당되는 값)를  없애고 싶다. remove 메소드를 사용           1

integers.removeLast() <-----  index에 마지막 요소를  없애고 싶다. removeLast 메소드를 사용            100   

integers.removeAll()  <-----    index에 모든 요소를 removeAll 없애고 싶다         

 

integers.count            <----- 몇개가 들어가 있는지를 확인하고 싶을때는  count                                     결과 0

 

 

//integers[0]                <--------  remveAll로 모두 지운상태에서

                                                    비어있는 배열상태이므로 잘못된 접근으로 취급되 강제종료가 됨

 

//Array<Double>와 [Double]는 동일한 표현 

 

//빈 Double Array 생성

var doubles: Array<Double> = [Double]() <----- 축약 리터럴표현, Double 타입의 Array 이며 ()는 생성

 

//빈 String Array 생성

var strings: Array<String> = [String]() <----- String 타입의 Array 이며 ()는 생성

 

//빈 Character Array 생성

var characters: [Character] = []   <------------ []는 새로운 빈 Array

 

let immutableArray = [1, 2, 3] <-------------- let을 사용하여 Array 를 선언하면 불변 Array

* let을 사용하게 되면 append 나 remove 를 사용할 수 없음 변경불가능한 Array기 때문*

 

 

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

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

var anyDictionary: Dictionary<String, Any> = [String: Any]()     <---Key는 String 타입이고, 값은 어떠한 타입의 값이든 가능

                                                                                                           <----[String: Any]() 로 축약가능 ()인스턴트 생성

anyDictionary["someKey"] = "value"                  <------ someKey라는 Key 값에 값(value)를 넣어준다.

anyDictionary["anotherKey"] = 100                    <------ anotherKey라는 Key 값에 값(100)를 넣어준다.

anyDictionary         <----- 확인해보게 되면 ["someKey": "value", "anotherKey": "100"]으로 표현되어 있음

 

// Key에 해당하는 값을 바꿔주고 싶을때 

anyDictionary["someKey"] = "dictionary"

anyDictionary         <----- 확인해보게 되면 ["someKey": "dictionary ", "anotherKey": "100"]로 바뀌어 있는 것을 확인 가능

 

//Key에 해당하는 값을 없애고 싶을때 2가지 방법(유사한 방법)

1. anyDictionary.removeValue(forKey: "anotherKey") <--- Key에 해당되는 값을 없애고 싶다

2. anyDictionary["someKey"] = nil  <----someKey에 해당하는 값을 없애고 싶다  

 

annyDictionary             <-----------결과[:] 비어 있는 것을 확인 할 수 있다.

let emptyDictionary: [String: String] = [:]    <------비어있는 Dictionary를 만들고

let initalizedDictionary: [String: String] = ["name": "Gyeongdeok", "gender": "male"]

--> let 으로 똑같이 name이라는 키에 Gyeongdeok, gender라는 키에 male을 넣어줄 수 있다 .

 

let someValue: String = initalizedDictionary["name"]

-> name이라는 key에 값이 String으로 설정해 놨는데 오류가 발생함

-> 이유: Key에 해당하는 값이 있을 수도 있고 없을 수도 없기 때문,

      값이 없으면 someValue 라는 String 타입에 상수에 값을 넣어줄 수 없기 떄문에 불확실함.

 

 

Set - 순서가 없고, 멤버가 유일한 컬렉션 

 

//빈 Int Set  생성

var integerSet: Set<Int> = Set<Int>()   <----Set는 축약 문법이 따로 없음

integerSet.insert(1)            <--------- insert 메소드를 이용해 요소를 추가할 수 있음

integerSet.insert(100) 

integerSet.insert(99)

integerSet.insert(99)

integerSet.insert(99)

 

integerSet                  <--------(100,99,1)    99를 세번추가했어도 Set는 중복된 값이 없다를 보장해줌

integerSet.contains(1)      <----- 결과 true

integerSet.contains(2)      <----- 결과 false

 

integerSet.remove(100)               

integerSet.removeFirst()

 

integerSet.count             <------------- 결과 1 100과 99를 없앴기 때문

 

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

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

 

let union: Set<Int> = setA.union(setB)         <-------Uinon을 이용해 합집합       결과:{2, 4, 5, 6, 7, 3, 1}

 

let sortedUnion: [Int] = union.sorted()          <-------정렬을 하고싶다 sorted     결과: {1, 2, 3, 4, 5, 6, 7}

 

let intersection: Set<Int> = setA.intersection(setB)  <------교집합 intersection  결과: {5, 3, 4}

 

let subtracting: Set<Int> = setA.subtracting(setB)   <-------차집합 subtracting   결과:{2, 1}

'Swift랑 친해지기 > Swift문법정리' 카테고리의 다른 글

08.함수고급  (0) 2021.12.21
07. 함수기본  (0) 2021.12.02
05. Any, AnyObject, nil  (0) 2021.12.01
기본 데이터 타입  (0) 2021.11.30
상수와 변수  (1) 2021.11.29