컬렉션 타입
- 여러 값들을 묶어서 하나의 변수나 이런 값들을 표현함
Array
- 순서가 있는 리스트 컬렉션(List 컬렉션 타입)
- 요소를 맨 뒤에 추가하고 싶을 경우 append라는 메서드 사용
- 해당 멤버를 가지고 있는지 파악하고 싶을 때는 contains 메서드 사용(해당 멤버가 포함되어 있으면 true, 없으면 false 값이 나옴)
- 인덱스에 해당하는 값을 없애고 싶을 때는 remove라는 메서드 사용
* 빈 Int Array 생성
var integers : Array<Int> = Array<Int>() // Int 타입의 Array라는 뜻
integers.append(1)
integers.append(100)
integers.remove(at: 0) // 0번째 인덱스에 해당하는 값(1) 삭제
integers.removeLast() // 마지막 인덱스에 해당하는 값(100) 삭제
integers.removeAll() // 모든 인덱스 삭제
* Array<Double>와 [Double]은 동일한 표현
빈 Double Array 생성
var doubles : Array<Double> = [Double]()
* 빈 String Array 생성
var strings : [String] = [String]()
* 빈 Character Array 생성
var characters : [Character] = [] // []는 새로운 빈 Array
* let을 사용하여 Array를 선언하면 불변 Array
let immutableArray = [1, 2, 3] // 변경 불가능한 Array
- append, remove 메서드는 사용불가
Dictionary
- 키와 값의 쌍으로 이루어진 컬렉션(hash map과 비슷함)
* Key가 String 타입이고 Value가 Any인 빈 Dictionary 생성
var anyDictionary : Dictionary<String(Key), Any(Value)> = [String : Any]()
anyDictionary["someKey"] = "value"
anyDictionary["anotherKey"] = 100
anyDictionary // ["someKey" : "vlaue", "anotherKey" : 100]
- someKey에 해당하는 값(value)이 있고, anotherKey에 해당하는 값(100)이 들어와 있음
* Key에 해당하는 값을 바꿔주고 싶을 때
anyDictionary["someKey"] = "dictionary" // 새로운 값을 넣어주면 됨
anyDictionary // ["someKey" : "dictionary", "anotherKey" : 100]
* Key에 해당하는 값을 없애고 싶을 때
anyDictionary.removeValue(forKey : "anotherKey") // anotherKey에 해당하는 값(100)을 삭제
anyDictionary["someKey"] = nil // someKey에 해당하는 값을 삭제할 때는 nil을 할당
let emptyDictionary : [String : String] = [:] // 빈 Dictionary
let initalizedDictionary : [String : String] = ["name" : "khon", "gender" : "male"]
Set
- 순서가 없고, 멤버가 유일한 컬렉션
- insert를 사용해 요소를 추가할 수 있음
- Set는 꼭 안에 중복된 값이 없다는 것을 보장하기 때문에 아무리 같은 값을 많이 넣어줘도 해당 값은 한 번만 출력
- 안에 요소가 있는지 없는지 contains로 확인 가능
- 삭제는 remove 사용
- count를 사용해서 Set안에 몇 개의 요소가 있는지 확인할 수 있음
* 빈 Int Set 생성
var integerSet : Set<Int> = Set<Int>() // Int 타입의 Set
integerSet.insert(1)
integerSet.insert(100)
integerSet.insert(99)
integerSet.insert(99)
integerSet.insert(99)
integerSet // 100, 99, 1
integerSet.contains(1) // 1 값이 있어서 true
integerSet.contains(2) // 2 값이 없으므로 false
integerSet.remove(100) // 100 삭제
integerSet.removeFirst() // 99 삭제
integerSet.count // 1
let setA : Set<Int> = [1, 2, 3, 4, 5]
let SetB : Set<Int> = [3, 4, 5, 6, 7]
let union : Set<Int> = setA.union(setB) // union을 이용해 합집합을 구함 (2, 4, 5, 6, 7, 3, 1)
let sortedUnion : [Int] = Union.sorted() // sorted 메서드를 이용해 같은 타입의 배열을 정렬 (1, 2, 3, 4, 5, 6, 7)
let intersectuon : Set<Int> = setA.intersection(setB) // intersection을 이용한 교집합 (5, 3, 4)
let subtracting : Set<Int> = setA.subtracting(setB) // subtracting을 이용한 차집합 (2, 1)